1. 9
  1.  

  2. 5

    The C standards (all versions) are quite clear that realloc(p,0) has to free p and return NULL;

    My copy doesn’t say that.

    1. 2

      I might be missing something, but this:

      Then someone came along and said “NULL should only be returned on failure”, and decided that their malloc would instead return unique non-NULL pointers.

      seems silly for malloc(0), which looks like it “shouldn’t cost” anything (but does, if that practice is used).

      Also, why would someone use malloc(0) instead of malloc(1) for this? Does it really bring significant savings?

      1. 3

        Error checking is complicated if malloc(0) returns null. Every check now has to be if (ptr == null && size != 0) or your program will report errors/quit unexpectedly. Or you can add if (size != 0) in front of every malloc call, which is probably even uglier.

        I think it’s hard to avoid 0 allocations in all cases. That’s the initial state for many algorithms. Code is a lot cleaner when you don’t have to write everything twice.

        Right or wrong, I tend to assume malloc(0) returns a unique pointer (most implementations do, by rounding up). It makes all the rest of the code consistent.

        1. 1

          Thanks. That makes a lot of sense. I realized, after I wrote that, that a NULL return is a sign of a typically very bad error condition (e.g. OOM).