简体   繁体   English

分配实例化结构时出现段错误?

[英]Seg fault when assigning an instantiated struct?

struct queens_arg {
  int board[64]; 
  int focus_idx;
};

struct queens_arg *args;
(*args).focus_idx = 0;

The code is as the following. 代码如下。 I get a seg fault (debugged) to occur on setting focus_idx = 0 . 在设置focus_idx = 0发生段错误(已调试)。 Why is this happening? 为什么会这样呢? How can I fix it? 我该如何解决? Thanks! 谢谢!

This occurs because you used a pointer, yet you didn't allocate anything. 发生这种情况是因为您使用了一个指针,但没有分配任何东西。 Hence you are writing into memory that is not yours. 因此,您正在写入不是您自己的内存。

You should first allocate args as follows: 您应该首先按以下方式分配args

struct queens_arg *args = malloc(sizeof(struct queens_arg));

Then you should check if args != NULL . 然后,您应该检查args != NULL If not, you can write to the memory you just allocated, using: 如果没有,您可以使用以下方法写入刚刚分配的内存:

args->focus_idx = 0;

The problem is that you're creating a pointer to a struct queens_arg , but you're not initializing it to point anywhere. 问题是您正在创建一个指向struct queens_arg的指针,但没有将其初始化为指向任何地方。 Consequently, when you write 因此,当你写

(*args).focus_idx = 0;

You're following a garbage pointer, causing the segfault at runtime. 您正在跟踪垃圾指针,从而在运行时导致段错误。

To fix this, make sure that you set up the pointer to point somewhere. 要解决此问题,请确保将指针设置为指向某处。 Here's how you can have it point to dynamically-allocated memory: 您可以通过以下方法将其指向动态分配的内存:

struct queens_arg* args = malloc(sizeof (struct queens_arg));

On a related note, you don't need to write 在相关说明中,您不需要写

(*args).focus_idx = 0;

You can instead use this shorthand: 您可以改用以下速记:

args->focus_idx = 0;

It means exactly the same thing, but is a bit easier to read. 它的含义完全相同,但更易于阅读。

您只声明了一个指向queens_arg结构的指针,实际上不存在任何结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM