Peter <> wrote:
> Thanks everyone for replying, I will definitely "free" after each
> "malloc". Something strange is that after calls to "free", the linked
> list is still accessible, the values are still there. Should I also
> assign NULL value to each node?
Memory may still be accessible via the pointer and it may even still
hold what it did before you called free(). But that's by pure chance,
what the pointer was pointing to may also have become inaccessible or
the memory it's pointing to may contain some other data. You simply
can't know and using the pointer after free() invokes undefined beha-
vior, i.e. everything can happen. So be very careful never to do that.
If setting the pointer to NULL after the call of free() helps you in
not using the pointer anymore then set it to NULL - but you don't
have to zero out the memory before free()ing it, that would just be
a waste of time. Setting the pointer to NULL is not required - all
you must do is refrain from using that pointer for anything at all
(including even just looking at its value).
int *x = malloc( 100 * sizeof *x );
....
free( x );
Both the following lines would invoke undefined behavior.
printf( "%d %d\n", x[ 11 ], *( x + 42 ); /* wrong! */
printf( "%p\n", ( void * ) x ); /* wrong! */
even though on some machines you might get away with doing that. All
you're allowed to do with 'x' after calling free() on it is to assign
a new value to it, e.g. by using a further call of malloc()
x = mallod( 20 * sizeof *x );
or setting it to NULL
Regards, Jens
--
\ Jens Thoms Toerring ___
\__________________________
http://www.toerring.de