views:

77

answers:

2

Hi, 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..

A: 

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.
sth
The first is not a real possibility. The second idea you give is confirmed by the data he posted from gdb. He's using an address off the stack in his data structure. You can know this because i is clearly on the stack.
Heath Hunnicutt
Thx, indeed, i created node->path outside as a local var, after i malloc it its fine now..
Louis
+3  A: 

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."

Heath Hunnicutt
Thx, indeed, i created node->path outside as a local var, after i malloc it its fine now
Louis
Sweet. I see you are new here. If you accept my answer, you can click the outline of a check-box. This converts your view to a filled-in green check-box, indicating you have accepted my answer. As a result, you get some points and I get 15. Also, now that you have called malloc() imagine that you were writing a program to run for weeks and weeks on end. In that case it is crucial to call free() at the time when you no longer keep track of previously allocated memory. For example, you might free() your data structure as you removed items from the path list.
Heath Hunnicutt