Allocated memory address clash
i don't understand how this happen. This is portion of my code..
int isGoal(Node *node, int startNode){
int i;
.
.
}
When i debug this using gdb i found开发者_运维知识库 out that 'i' was allocated at the memory address that have been previously allocated.
(gdb)print &node->path->next
$26 = (struct intNode **) 0xffbff2f0
(gdb) print &i
$22 = (int *) 0xffbff2f0
node->path->next has been already defined outside this function. But as u can see they share the same address which at some point make the pointer point to another place when the i counter is changed.
I compiled it using gcc on solaris platform Any helps would be really appreciated..
The memory for i
is taken from the stack, or what in C is sometimes called "automatic storage."
The contents of memory allocated from the stack are no longer valid after the function declaring that storage has returned. For example, your isGoal()
function allocates stack storage for the variable i
and the storage exists only until the point in time when isGoal()
returns.
The reason you see the address of i
, &i
has already existed during your program is that the stack memory area is continually reused. Prior to what you see in gdb, you have stored the address of a stack variable in node->path->next
.
To obtain memory which remains valid after the allocating function has returned, you must use malloc()
and free()
to obtain what is called "dynamic memory" or, sometimes, memory from the "heap."
Two possibilities:
- You have compiled with optimizations and this is confusing gdb (for example
i
could be optimized away, so that it actually hasn't any address) node->path
doesn't point to correctly allocated memory. For example that pointer could have been set to point to an object on the stack that subsequently went out of scope.
精彩评论