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.
The result of calling malloc(0) to allocate 0 bytes is implementation-defined. In this example, a dynamic array of integers is allocated to store size elements. However, if size is 0, the call to malloc(size) may return a reference to a block of memory of size 0 instead of a null pointer.
Just because malloc returns zero-initialized memory the first time doesn't mean you can count on it in general. It also could be that the memory was set to 0 by the operating system or something and malloc had nothing to do with it.
When you call malloc a second time, it has no way of knowing you are doing anything with newPtr . It merely allocates new space and returns a pointer to it. Then that new pointer is assigned to newPtr , which erases the old value that was in newPtr .
When you no longer need a block that you got with malloc , use the function free to make the block available to be allocated again. The prototype for this function is in stdlib. h .
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:
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):
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With