Why does malloc(0) return a non-null address in Windows?

c, malloc, memory-management

Solution

It's just the minimum size you're requesting. And since there are no zero-length blocks in the Win32 heap, you can:

void *p = malloc(0);
// ... do some stuff in between...
realloc(p, n);

Which should mostly result in reusing a block of the heap (if you're lucky and the new size is small). A minor opportunist optimization (or a slow-down, depending on the context and blood coffee-levels).

This is a simplified example. The actual situation could be a class that allocates a buffer when it's created and also allows to grow it. If the inputs are annoying to control, you could just let it do that zero-sized buffer allocation.

Problem

The code below returns an address when executed in Windows, though I was expecting it to return NULL. ``` int main() { char *ptr = NULL; ptr = malloc(0); printf("malloc returned = %u\n", ptr); } ``` What could have prompted such an implementation of malloc? Is there any reason behind it? Since, this is a 0 byte memory, I didn't experiment writing any data. But, can this memory be used for anything at all?

Original source