s_**********@rediffmail.com (s.subbarayan) writes:
In one of our projects in a document about C coding standard it is
stated as
"Always check a pointer is NULL before calling free. Always set a
free'd pointer to NULL to try to protect it from being used again
later and causing memory leaks."
My doubt is,"Is this standard practice every where?"Also is it valid
to free a pointer after the value is set to NULL?Because AFAIK,NULL
means it points to nowhere!
Another doubt in the similar manner:I am not able to understand the
behaviour of this code:
char *ptr;
if ((ptr = (char *)malloc(0)) ==
NULL)
puts("Got a null pointer");
else
puts("Got a valid pointer");
The cast is superfluous; you can change
ptr = (char *)malloc(0)
to
ptr = malloc(0)
malloc() returns a pointer to void, which is implicitly converted to
whatever pointer type you assign it to. But that's a minor point.
This piece of code gives "Got a valid pointer".How come when I specify
a size of zero,memory is allocated and ptr becomes a valid pointer?
I am not able to get the proper reason ,can anyone enlighten me the
reason behind this?
Here's what the standard says:
For malloc(), calloc(), and realloc():
If the space cannot be allocated, a null pointer is returned. If
the size of the space requested is zero, the behavior is
implementation defined: either a null pointer is returned, or the
behavior is as if the size were some nonzero value, except that
the returned pointer shall not be used to access an object.
For free()
The free function causes the space pointed to by ptr to be
deallocated, that is, made available for further allocation. If
ptr is a null pointer, no action occurs.
There's no need to check whether a pointer is null before calling
free; free(NULL) is perfectly valid, and does nothing. (There may be
some very old pre-ANSI implementations that misbehave on free(NULL).
There's usually no need for coding standards to cater to such
implementations.)
Setting a pointer to NULL after freeing it:
free(ptr);
ptr = NULL;
provides some slight protection, but it's not absolute. For example:
ptr = malloc(whatever);
another_ptr = ptr;
free(ptr);
ptr = NULL;
Here I've set ptr to NULL, but another_ptr still contains a copy of
the (now invalid) pointer value. I won't argue that you *shouldn't*
set the pointer to NULL, but don't expect it to catch all your errors;
there's no substitute for careful programming that avoids referring to
free()d pointers.
As for malloc(0), it can return either a null pointer or a valid
pointer (though one that's not particularly useful). If your program
might call malloc() with an argument of 0, you'll need to deal with
both possibilities.
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.