Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Except that I left out a "should".

While it would be good if malloc(0) always returned a pointer, you can't rely on malloc(0) returning NULL just for errors. There's not even a guarantee that malloc(0) does the same thing every time.

Note that "returning a pointer to the byte after the internal malloc header" means that malloc(0) == malloc(0), breaking the unique pointer guarantee unless malloc(0) actually causes an allocation.

However, allocating in malloc(0) means that while(1) malloc(0); can cause a segfault, which would be a surprising thing.



No, it doesn't.

malloc(0) != malloc(0) because the internal malloc header is different for each allocation.

Asking for a malloc of size n, means internally the malloc library allocates n + h, where h is the internal malloc header size. So there is always an allocation being done for at least a size of h, just with an internal bookkeeping "size" field set to zero.

and yes, while(1) malloc(0); will eventually run out of memory, counter-intuitively :-).




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: