This question already has an answer here:
- what's the point in malloc(0)? 16 answers
Very simple question, I made the following program :
#include <stdlib.h>
int main(int argc, char ** argv)
{
void * ptr;
ptr = malloc(0);
free(ptr);
}
And it does not segfault on my machine. Is it a portable behaviour of stdlib malloc and free, or am I looking for trouble ?
Edit : What seems non portable is the value returned by malloc. The question is about the malloc(0) + free combination, not the value of ptr.
In my experience, I have seen that malloc (0) returns a pointer which can be freed. But, this causes SIGSEGV in later malloc() statements. And this was highly random.
When I added a check, for not to call malloc if size to be allocated is zero, I got rid of this.
So, I would suggest not to allocate memory for size 0.
-Ashutosh
It's allowed to return NULL, and it's allowed to return a non-NULL pointer you can't dereference. Both ways are sanctioned by the standard (7.20.3):
Though it might be legal C/C++, it is indicative a bigger problems. I generally call it 'pointer slopiness'.
See "Do not make assumptions about the result of malloc(0) or calloc(0)", https://www.securecoding.cert.org/confluence/display/seccode/VOID+MEMxx-A.+Do+not+make+assumptions+about+the+result+of+malloc%280%29+or+calloc%280%29.
The behaviour is implementation defined, you will receive either a NULL pointer or an address. Calling free for the received pointer should however not cause a problem since:
Sorry for the trouble, I should have read the man pages :
malloc() allocates size bytes and returns a pointer to the allocated memory. The memory is not cleared. If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().
free() frees the memory space pointed to by ptr, which must have been returned by a previous call to malloc(), calloc() or realloc(). Otherwise, or if free(ptr) has already been called before, undefined behavior occurs. If ptr is NULL, no operation is performed.
It seems it is true at least for the gnu libc
According to the c standard
7.20.3 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.