Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of malloc(0)?

Tags:

c

malloc

I just saw this code:

artist = (char *) malloc(0);

...and I was wondering why would one do this?

like image 563
jldupont Avatar asked Jan 07 '10 17:01

jldupont


People also ask

What is the point of using malloc 0?

According to the specifications, malloc(0) will return either "a null pointer or a unique pointer that can be successfully passed to free()". This basically lets you allocate nothing, but still pass the "artist" variable to a call to free() without worry.

Do you have to free malloc 0?

Yes, free(malloc(0)) is guaranteed to work.

What does malloc point to?

malloc is used to allocate memory. You can use a pointer by either allocating it with malloc or making it point to an already allocated portion of memory.

Why is malloc length 1?

The + 1 is to make room for the NUL terminator. If you want a string of length n , your array has to be of length n + 1 ; n spaces for the n characters of the string, and 1 space for the terminator. By the way, you shouldn't cast the return value of malloc . It will make your code easier to change in the future.


2 Answers

According to the specifications, malloc(0) will return either "a null pointer or a unique pointer that can be successfully passed to free()".

This basically lets you allocate nothing, but still pass the "artist" variable to a call to free() without worry. For practical purposes, it's pretty much the same as doing:

artist = NULL;
like image 112
Reed Copsey Avatar answered Oct 20 '22 06:10

Reed Copsey


The C standard (C17 7.22.3/1) says:

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.

So, malloc(0) could return NULL or a valid pointer that may not be dereferenced. In either case, it's perfectly valid to call free() on it.

I don't really think malloc(0) has much use, except in cases when malloc(n) is called in a loop for example, and n might be zero.

Looking at the code in the link, I believe that the author had two misconceptions:

  • malloc(0) returns a valid pointer always, and
  • free(0) is bad.

So, he made sure that artist and other variables always had some "valid" value in them. The comment says as much: // these must always point at malloc'd data.

like image 42
Alok Singhal Avatar answered Oct 20 '22 05:10

Alok Singhal