Re: link pointer access problem
- From: jameskuyper <jameskuyper@xxxxxxxxxxx>
- Date: Thu, 17 Sep 2009 07:45:29 -0700 (PDT)
vichy.kuo@xxxxxxxxx wrote:
Dear all:
Below is my program:
#include<stdio.h>
typedef struct{
int b_value;
}B;
typedef struct{
B* next;
int a_value;
}A;
int main(void)
{
A a;
At this point, a is uninitialized; all of it's members have
indeterminate values. That means, in particular, that a.next may have
a trap representation.
//B* pb;
a.a_value=12;
//pb=a.next;
//pb->b_value=23;
You don't have any objects of type B in your program, and you have not
set a.next to point to any such object. You haven't even set a.next to
be a null pointer (though that would not help, in this case). At this
point, a.next still has an indeterminate value. Therefore, the
behavior of the next statement is undefined:
a.next->b_value=23;
The same is true of this statement, for the same reason:
printf("b_value=%dvn",a.next->b_value);
//printf("b_value=%dvn",pb->b_value);
return 0;
}
The program will get segment fault or
That is an entirely reasonable and plausible result from attempting to
dereference a pointer with an indeterminate value.
... compiler will say "request for
member 'b_value' in something not a structure or union".
However, I see no justification for such a message. A smart compiler
could have recognized at compile time that your code dereferences an
uninitialized pointer; but if so, this message seems like a very odd
way to describe that fact.
The program will be fine if I unmark "//" part, which is the way that
people usually to access link list.
It will not be fine. Even simply copying the value of a.next to pb has
undefined behavior, if a.next contains a trap representation. If
a.next doesn't contain a trap representation, it's indeterminate value
will be copied to pb, with no guarantee that it points at any location
that can be safely dereference. However, since the behavior is
undefined, one of the possible results is that, this time, the
uninitialized value of a.next happens to point at memory that you can
safely read and write to.
"next" is an element of A, so a.next should be fine.
"a.next" is a pointer which point to B,
Correct.
... so a.next->b_value seems ok.
Not until a.next has been given a value that points at an actual B
object.
.
- References:
- link pointer access problem
- From: vichy.kuo@xxxxxxxxx
- link pointer access problem
- Prev by Date: Re: link pointer access problem
- Next by Date: Re: link pointer access problem
- Previous by thread: Re: link pointer access problem
- Next by thread: Re: link pointer access problem
- Index(es):
Relevant Pages
|