开发者

Accessing a pointer through a nested structure

struct x {
  int *u;
};

struct y {
  struct x *z;
};

int main()
{
  static y b;
  static int g=7;
  b.z->u=&g;
}

The statement b.z->u=&g gives a segmentation error. If I remove the static in front of int g:

int g=7;开发者_开发技巧
b.z->u=&g;  

The code executes properly.


b.z is not yet initialized. You initialize b with:

static y b;

but its member field z is still a null pointer (pointing so some random location). So accessing its member u results in an segmentation error as you are accessing some random memory.

I suppose that like this should work (did not try):

static y b;
static x c;
static int g=7;
b.z = &c;
b.z->u=&g;

Why your second example works, I do not know. I suspect it is due to 'luck'...


Because b.z hasn't been set to point anywhere useful. It's currently just a NULL pointer.*

You need to do something along the lines of:

b.z = malloc(sizeof(*b.z));

first (i.e. create an actual object).

Remember to free this at some point.


* Note that it's only NULL because b is declared as static. If b were non-static, it would be pointing at somewhere random in memory.


It will give you a segmentation error, because what you're doing is undefined behavior. You're accessing the z pointer of the structure without initializing it (that is, without giving it a memory space to point to). The fact that it is not giving you a segmentation error in the case the variable is not static is not important, as the whole access to an uninitialized pointer is wrong.


You never allocated memory for your b.z. Your b.z contains an uninitialized garbage value, which is why trying to dereference b.z (in b.z->u) causes a segmentation fault.

P.S. You declared your objects static, which means that b.z initially contains a null value (not an "uninitialized garbage value" as I stated above). Nevertheless, dereferencing a null pointer is also undefined.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜