Hi
I have the following piece of code.
int *p;
p = malloc(10);
int *j;
j = p;
free(p);
Is this legal ? will j still point to the same
memory that p pointed to earlier ?
Can I access that memory using j ?
I read somewhere that even though free is
called, the memory is still available.
so in my case j should still point to that
memory right ?
MC
[ from the FAQ ]
--------------------------------------------------------------------
7.20: You can't use dynamically-allocated memory after you free it,
can you?
A: No. Some early documentation for malloc() stated that the
contents of freed memory were "left undisturbed," but this ill-
advised guarantee was never universal and is not required by the
C Standard.
Few programmers would use the contents of freed memory
deliberately, but it is easy to do so accidentally. Consider
the following (correct) code for freeing a singly-linked list:
struct list *listp, *nextp;
for(listp = base; listp != NULL; listp = nextp) {
nextp = listp->next;
free(listp);
}
and notice what would happen if the more-obvious loop iteration
expression listp = listp->next were used, without the temporary
nextp pointer.
References: K&R2 Sec. 7.8.5 p. 167; ISO Sec. 7.10.3; Rationale
Sec. 4.10.3.2; H&S Sec. 16.2 p. 387; CT&P Sec. 7.10 p. 95.
7.21: Why isn't a pointer null after calling free()?
How unsafe is it to use (assign, compare) a pointer value after
it's been freed?
A: When you call free(), the memory pointed to by the passed
pointer is freed, but the value of the pointer in the caller
probably remains unchanged, because C's pass-by-value semantics
mean that called functions never permanently change the values
of their arguments. (See also question 4.8.)
A pointer value which has been freed is, strictly speaking,
invalid, and *any* use of it, even if is not dereferenced, can
theoretically lead to trouble, though as a quality of
implementation issue, most implementations will probably not go
out of their way to generate exceptions for innocuous uses of
invalid pointers.
References: ISO Sec. 7.10.3; Rationale Sec. 3.2.2.3.
===================================================================
Hope this helps,
-dj