129

I just saw this code:

artist = (char *) malloc(0);

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

Lii
  • 9,906
  • 6
  • 53
  • 73
jldupont
  • 82,560
  • 49
  • 190
  • 305

17 Answers17

126

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;
Reed Copsey
  • 522,342
  • 70
  • 1,092
  • 1,340
  • that's what I had guessed. Would this constitute a good "cross-platform" strategy? – jldupont Jan 07 '10 at 17:48
  • 54
    Personally, I think setting to NULL is a better cross-platform strategy, since free() is guaranteed (by spec) to work fine on NULL as input. – Reed Copsey Jan 07 '10 at 17:50
  • 3
    As mentioned by C. Ross, some platforms, technically, could return a pointer here (that is a "unique pointer that can be passed to free"), but if you're treating this as a char*, that may give you an invalid, non-terminated char. It could be dangerous to rely on this in cross-platform situations. – Reed Copsey Jan 07 '10 at 17:51
  • Note that this also happens when you declare an empty struct where `sizeof` will return `0`. – IluTov Oct 18 '14 at 12:51
  • 11
    Really wish the specs would say "safely passed to realloc" as well -.- – hanshenrik Jul 13 '15 at 14:59
  • 1
    @NSAddict "empty struct where sizeof will return 0", please provide an example, sounds like a language extension. – chux - Reinstate Monica Sep 12 '16 at 22:33
  • @chux `struct fred {};`? – wizzwizz4 May 27 '17 at 19:04
  • @wizzwizz4 Interesting, when I compile I get " warning: struct has no members [-Wpedantic]" with `struct fred {};`. Does your compiler raise any flags? – chux - Reinstate Monica May 31 '17 at 12:43
  • @chux I haven't tried it. However, `-Wpedantic` shows warnings for _everything_ pointless or silly. (The impressive ones are when you try to golf in C.) – wizzwizz4 May 31 '17 at 20:23
  • Were there any ancient C compilers that did not properly handle `NULL` on calls to `free`? If so, that would make code like what op posted make more sense to me along with code I've seen littered through legacy codebases like: `if (ptr) free(ptr);` -- otherwise all such code seems pointless, wasteful, and maybe naive about standard behavior.... but if such compilers/library implementations of `free` ever existed that failed to handle `NULL` properly in some distant past, then such code would make so much more sense. –  Dec 29 '17 at 20:29
  • 2
    @hanshenrik Who says you can't? [`realloc()`](http://pubs.opengroup.org/onlinepubs/009695399/functions/realloc.html) allows you to pass any valid pointer returned by `malloc()`. Should be enough. – glglgl Apr 03 '19 at 11:18
52

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.

Lundin
  • 155,020
  • 33
  • 213
  • 341
Alok Singhal
  • 82,703
  • 18
  • 122
  • 153
11

malloc(0) behaviour is implementation specific. The library can return NULL or have the regular malloc behaviour, with no memory allocated. Whatever it does, it must be documented somewhere.

Usually, it returns a pointer that is valid and unique but should NOT be dereferenced. Also note that it CAN consume memory even though it did not actually allocate anything.

It is possible to realloc a non null malloc(0) pointer.

Having a malloc(0) verbatim is not much use though. It's mostly used when a dynamic allocation is zero byte and you didn't care to validate it.

Coincoin
  • 25,460
  • 7
  • 49
  • 73
  • 10
    `malloc()` must keep "housekeeping information" somewhere (this size of the block allocated for example, and other auxiliary data). So, if `malloc(0)` does not return `NULL`, it will use memory to store that information, and if not `free()`d, will constitute a memory leak. – Alok Singhal Jan 07 '10 at 18:00
  • Malloc implementations perform record keeping which could add a certain amount of data per pointer returned on top of the size requested. – user7116 Jan 07 '10 at 18:02
  • 1
    Memory consumed and memory allocated does not mean the same thing. In this very case, most implementation will return a unique pointer. This mean a part of the address space needs to be sacrificed for that pointer. Depending on the allocator, this might actually mean it will allocate 1 byte or more. – Coincoin Jan 07 '10 at 18:02
  • @jldupont: In practice if an implementation does take this option, then it's because it has gone through all the motions of doing an allocation, but with size 0. The overhead will be the same as for any other allocation. Even if it did something different, it would still have to reserve some address space, and make a record somewhere that it has done so. – Steve Jessop Jan 07 '10 at 18:03
  • @Steve: of course... but which implementation would do this anyways? – jldupont Jan 07 '10 at 18:04
  • 1
    *The library can do whatever it wants* - well, it can either return a unique pointer that no other `malloc()` will return, or return `NULL`. – Alok Singhal Jan 07 '10 at 18:07
  • @jldupont: you want a list of memory allocators which return non-NULL for `malloc(0)`? I don't know, sorry, it's not something I've ever felt the need to rely on. I wouldn't consider it unreasonable, though: returning NULL in this case is basically an early-out speed optimisation, for a case that probably never happens. Waste of good ASCII characters, unless your allocation code would special-case 0 anyway. – Steve Jessop Jan 07 '10 at 18:17
  • @Steve: I was just curious, that's all. Thanks. – jldupont Jan 07 '10 at 18:28
  • 1
    @jldupont: At least the Microsoft C Run-Time library returns a unique pointer for `malloc(0)`. However, in the very same implementation of the standard C library, `realloc(ptr, 0)` frees `ptr` and returns NULL. – Medinoc Apr 12 '18 at 14:05
6

There's an answer elsewhere on this page that begins "malloc(0) will return a valid memory address and whose range will depend on the type of pointer which is being allocated memory". This statement is incorrect (I don't have enough reputation to comment on that answer directly, so can't put this comment directly under there).

Doing malloc(0) will not automatically allocate memory of correct size. The malloc function is unaware of what you're casting its result to. The malloc function relies purely on the size number that you give as its argument. You need to do malloc(sizeof(int)) to get enough storage to hold an int, for example, not 0.

Krellan
  • 301
  • 3
  • 5
3

malloc(0) doesn't make any sense to me, unless the code is relying on behaviour specific to the implementation. If the code is meant to be portable, then it has to account for the fact that a NULL return from malloc(0) isn't a failure. So why not just assign NULL to artist anyway, since that's a valid successful result, and is less code, and won't cause your maintenance programmers to take time figuring it out?

malloc(SOME_CONSTANT_THAT_MIGHT_BE_ZERO) or malloc(some_variable_which_might_be_zero) perhaps could have their uses, although again you have to take extra care not to treat a NULL return as a failure if the value is 0, but a 0 size is supposed to be OK.

Steve Jessop
  • 257,525
  • 32
  • 431
  • 672
3

There are a lot of half true answers around here, so here are the hard facts. The man-page for malloc() says:

If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().

That means, there is absolutely no guarantee that the result of malloc(0) is either unique or not NULL. The only guarantee is provided by the definition of free(), again, here is what the man-page says:

If ptr is NULL, no operation is performed.

So, whatever malloc(0) returns, it can safely be passed to free(). But so can a NULL pointer.

Consequently, writing artist = malloc(0); is in no way better than writing artist = NULL;

cmaster - reinstate monica
  • 33,875
  • 7
  • 50
  • 100
  • 1
    Too bad the implementation isn't allowed to return a non-null, non-unique pointer. That way, `malloc(0)` could return, say, 0x1, and `free()` could have a special-case check of 0x1 just as it has for 0x0. – Todd Lehman Aug 21 '15 at 07:24
  • 3
    @Todd Lehman An implementation may do as you suggest. The C spec does not specify the result must be "`NULL`, or a unique pointer". instead 'either a null pointer or a pointer to the allocated space". There is no _unique_ requirement. OTOH, returning a non-unique special value may disrupt code that counts on unique values. Perhaps a corner case question for SO. – chux - Reinstate Monica Sep 12 '16 at 22:44
  • `man` may as well document the implementation-defined form used in *nix. In this case it doesn't, but it still isn't a canonical source for general C. – Lundin Jan 28 '19 at 10:01
  • @Lundin True. But the man-pages are much more accessible than the C standard, and the man-pages on GNU/Linux systems generally document quite well which standard(s) the implementation follows. Along with information of which parts adhere to which standard, should they differ. I have the feeling that they both want to be precise, and advertise every single bit that's a GNU extension... – cmaster - reinstate monica Jan 28 '19 at 20:04
3

Why you shouldn't do this...

Since malloc's return value is implementation dependent, you may get a NULL pointer or some other address back. This can end up creating heap-buffer overflows if error handling code doesn't check both size and returned value, leading to stability issues (crashes) or even worse security issues.

Consider this example, where further accessing memory via returned address will corrupt heap iff size is zero and implementation returns a non NULL value back.

size_t size;
 
/* Initialize size, possibly by user-controlled input */
 
int *list = (int *)malloc(size);
if (list == NULL) {
  /* Handle allocation error */
}
else {
  /* Continue processing list */
}

See this Secure Coding page from CERT Coding Standards where I took the example above for further reading.

Shipof123
  • 233
  • 2
  • 11
auselen
  • 25,874
  • 4
  • 67
  • 105
  • The link has been moved: https://wiki.sei.cmu.edu/confluence/display/c/MEM04-C.+Beware+of+zero-length+allocations – alx Dec 30 '19 at 23:27
2

Admittedly, I have never seen this before, this is the first time I've seen this syntax, one could say, a classic case of function overkill. In conjunction to Reed's answer, I would like to point out that there is a similar thing, that appears like an overloaded function realloc:

  • foo is non-NULL and size is zero, realloc(foo, size);. When you pass in a non-NULL pointer and size of zero to realloc, realloc behaves as if you’ve called free(…)
  • foo is NULL and size is non-zero and greater than 1, realloc(foo, size);. When you pass in a NULL pointer and size is non-zero, realloc behaves as if you’ve called malloc(…)

Hope this helps, Best regards, Tom.

t0mm13b
  • 32,846
  • 7
  • 71
  • 106
1

To actually answer the question made: there is no reason to do that

Paolo
  • 13,439
  • 26
  • 59
  • 82
0

In Windows:

  • void *p = malloc(0); will allocate a zero-length buffer on the local heap. The pointer returned is a valid heap pointer.
  • malloc ultimately calls HeapAlloc using the default C runtime heap which then calls RtlAllocateHeap, etc.
  • free(p); uses HeapFree to free the 0-length buffer on the heap. Not freeing it would result in a memory leak.
Jamal
  • 747
  • 7
  • 22
  • 31
sam msft
  • 413
  • 4
  • 14
0

Its actually quite useful, and (obviously IMHO), the allowed behavior of returning a NULL pointer is broken. A dynamic pointer is useful not only for what it points at, but also the fact that it's address is unique. Returning NULL removes that second property. All of the embedded mallocs I program (quite frequently in fact) have this behavior.

Scott Franco
  • 183
  • 11
-1

Not sure, according to some random malloc source code I found, an input of 0 results in a return value of NULL. So it's a crazy way of setting the artist pointer to NULL.

http://www.raspberryginger.com/jbailey/minix/html/lib_2ansi_2malloc_8c-source.html

Doug T.
  • 59,839
  • 22
  • 131
  • 193
-1

malloc(0) will return NULL or a valid pointer which can be rightly passed to free. And though it seems like the memory that it points to is useless or it can't be written to or read from, that is not always true. :)

int *i = malloc(0);
*i = 100;
printf("%d", *i);

We expect a segmentation fault here, but surprisingly, this prints 100! It is because malloc actually asks for a huge chunk of memory when we call malloc for the first time. Every call to malloc after that, uses memory from that big chunk. Only after that huge chunk is over, new memory is asked for.

Use of malloc(0): if you are in a situation where you want subsequent malloc calls to be faster, calling malloc(0) should do it for you (except for edge cases).

Sagar Bhosale
  • 330
  • 2
  • 4
  • 1
    Writing to `*i` may not crash in your case, but it's undefined behavior nevertheless. Watch out for nasal demons! – John Dvorak Jan 01 '14 at 09:33
  • 1
    Yes. That is true. It is implementation specific. I have verified it on MaxOS X and some Linux distribution. I have not tried it on other platforms. Having said that, the concept that I have described has been described in the book "The C programming language" by Brain Kernighan and Dennis Ritchie. – Sagar Bhosale Jan 01 '14 at 22:53
  • I know: super late comment on this question. But there is _sometimes_ a use for `malloc(0)` that isn't mentioned. On those implementations where it returns a non-NULL value, especially in a DEBUG build, it likely allocates MORE than you asked for, and gives you the pointer to just past its internal header. This allows you to get a _feel_ for actual memory usage if you get this before and after a series of allocations. e.g.: `void* before = malloc(0); ... void* after = malloc(0); long long total = after - before;` or some such. – Jesse Chisholm Feb 24 '17 at 19:06
  • I read "The C programming language" by Brain Kernighan and Dennis Ritchie and I don't remember it saying anything about `malloc(0)`. Could you please say which chapter are you referring too? Providing an exact quote would be nice too. – Андрей Беньковский Oct 15 '17 at 08:19
-3

Here is the analysis after running with valgrind memory check tool.

==16740== Command: ./malloc0
==16740==
p1 = 0x5204040
==16740==
==16740== HEAP SUMMARY:
==16740==     in use at exit: 0 bytes in 0 blocks
==16740==   total heap usage: 2 allocs, 2 frees, 1,024 bytes allocated
==16740==
==16740== All heap blocks were freed -- no leaks are possible

and here's my sample code:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
   //int i;
   char *p1;

   p1 = (char *)malloc(0);
   printf("p1 = %p\n", p1);

   free(p1);

   return 0;

}

By default 1024 bytes is allocated. If I increase the size of malloc, the allocated bytes will increase by 1025 and so on.

-5

According to Reed Copsey answer and the man page of malloc , I wrote some examples to test. And I found out malloc(0) will always give it a unique value. See my example :

char *ptr;
if( (ptr = (char *) malloc(0)) == NULL )
    puts("Got a null pointer");
else
    puts("Got a valid pointer");

The output will be "Got a valid pointer", which means ptr is not null.

Community
  • 1
  • 1
Neal
  • 84
  • 3
-7

Just to correct a false impression here:

artist = (char *) malloc(0); will never ever return NULL; it's not the same as artist = NULL;. Write a simple program and compare artist with NULL. if (artist == NULL) is false and if (artist) is true.

Jamal
  • 747
  • 7
  • 22
  • 31
-8

malloc(0) will return a valid memory address and whose range will depend on the type of pointer which is being allocated memory. Also you can assign values to the memory area but this should be in range with the type of pointer being used. You can also free the allocated memory. I will explain this with an example:

int *p=NULL;
p=(int *)malloc(0);
free(p);

The above code will work fine in a gcc compiler on Linux machine. If you have a 32 bit compiler then you can provide values in the integer range, i.e. -2147483648 to 2147483647. Same applies for characters also. Please note that if type of pointer declared is changed then range of values will change regardless of malloc typecast, i.e.

unsigned char *p=NULL;
p =(char *)malloc(0);
free(p);

p will take a value from 0 to 255 of char since it is declared an unsigned int.

Chris
  • 93,263
  • 50
  • 204
  • 189
  • 5
    Krellan is right in pointing out that this answer is wrong: `malloc()` does not know anything about the cast (which is actually entirely superfluent in C). Dereferencing the return value of `malloc(0)` will invoke undefined behavior. – cmaster - reinstate monica Apr 16 '14 at 19:28