zero size malloc

shodanex picture shodanex · Jul 2, 2009 · Viewed 32.4k times · Source

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.

Answer

Key picture Key · Jul 2, 2009

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:

  • free(NULL) is ok, no operation is done
  • free(address) is ok, if address was received from malloc (or others like calloc etc.)