10

While reading an answer here, I saw this code:

char ** v = malloc(0);
while ((r = strtok(s, " ")) != NULL) {
    char ** vv = realloc(v, (n+1)*sizeof(*vv));

The thing that bugged me was the call to malloc with an argument of zero. According to the standard, this will return either NULL or a pointer that can be successfully passed to free. I know that this does not invoke any problems (except for if you do stuff like if (v == NULL) or similar) but is there any practical reason whatsoever to prefer malloc(0) instead of NULL?

I saw the argument "to indicate the goal of that pointer is to be given to realloc later". To me that sounds like a pretty strange argument. I cannot see the value of that convention at all. First because it's an extra function call that's not needed. And second because the value of telling that you will use realloc later seems almost zero. And according to the answers on this question it does not seem to be any technical benefits whatsoever.

Personally, if I ever felt the need to tell that realloc would be used later I'd do this:

char **v = NULL; // Will be realloced later

or give it a name that makes that intention clear. I would not use a strange unmotivated function call. But IMHO, just initializing it to NULL is a very clear indication that SOMETHING will be done to it later on. I don't see the value of knowing in advance that it's realloc. What's next? A convention saying that malloc(0*0) indicates that strdup will be used later?

So to sum it up, these are the cons that I know of:

  • An extra unnecessary function call
  • Looks weird if you don't know that it indicates later realloc (and still looks weird to me anyway)
  • May return a valid pointer that should not be dereferenced (just strange)
  • May allocate memory that you cannot use (quite pointless)
  • Less predictable. You may get NULL. You may get something else.

Pros:

  • ?

The only sensible explanation I can think of that this habit may come from is that it is something from very early C, before NULL became a part of stddef.h and calling malloc(0) was the only portable way to get a pointer that was guaranteed to be safe to be passed to free without allocating anything. Could that be the case?

So is this really an accepted convention for indicating a later realloc? If so, is it a good convention? Does it have any benefits that I fail to see?

EDIT:

There is a related question on SO: What's the point of malloc(0)?

EDIT2:

Clarification:

I'm not talking about malloc(n) where n happens to be zero in some cases. I'm talking about calling malloc(0) on purpose.

  • 1
    just initializing it to NULL is a very clear indication that SOMETHING will be done to it later on You left out "and if it remains NULL that's a clear indication that SOMETHING was NOT done to it." Using malloc(0) removes that information. – Andrew Henle Jun 7 at 16:24
  • Have you omitted any code for simplicity? Where does the value of n come from? What happens to v after this? For these two lines v could be NULL without affecting functionality. My guess is the code here is trying to allocate a buffer big enough to hold a token on the heap, and the code assumes the realloc function will only grow the allocation and never shrink it and does this efficiently. (probably true except for the efficient part) But why there is both a v and a vv variable isn't clear from the code quoted. – MZB Jun 9 at 3:30
  • @MZB I cannot see how it would matter. Can you demonstrate something where initializing to malloc(0) instead of NULL is a good idea? The reason for vv is the standard one, which is a v=vv later. – klutt Jun 9 at 7:40
  • @klutt With the code as illustrated, there's no reason to have separate v and vv variables - in fact it looks like a bug. Perhaps v is checked to be non-zero in some following logic? With just the snippet to go on, it's impossible to tell why both variables exist. (Although a likely possibility is the author didn't have the realloc manual page to hand and couldn't remember it's treatment of NULL values). – MZB Jun 10 at 18:57
  • @MZB The reason is that if malloc fails, then you can keep the data you have and recover. But the question is not why both exist. It's about malloc(0) – klutt Jun 10 at 21:28
8

In my opinion, that is a horrible paradigm.

I see absolutely no pros and at least three substantial cons.

Needless code complexity

Since malloc(0) can return NULL, the code has to be written to handle that anyway.

And since malloc(0) can also produce a non-NULL result, the code also has to be written in a way to handle a non-NULL pointer.

Pointer state loses all meaning

By potentially producing a pointer that can not be dereferenced, malloc(0) removes a critical distinction between NULL and non-NULL pointers: the distinction where NULL pointers mean "there's nothing here" and non-NULL pointers mean "here's some actual valid data".

The NULL/non-NULL state of a pointer loses all information.

Using malloc(0) renders the almost universal use of code such as if (ptr) ... or if (ptr != NULL) ... useless by removing information from the state of a pointer simply being non-NULL. This simple code

if ( ptr )
{
    ...

would have to be

if ( ptr && pointerActuallyPointsToActualObject )
{
    ...

And now there are two values - the pointer and its "validity flag" that have to be kept in sync and passed around.

Code such as

Foo *dataPtr = getNewFoo();

would no longer work should the prospective new Foo * being returned from the function be initialized with malloc(0) because a non-NULL pointer would no longer mean "no new Foo for you!".

Substantially Increased Potential for Heisenbugs

Any non-NULL pointer that can not be safely dereferenced creates serious potential Heisenbugs.

In general, any erroneous dereference of a NULL pointer results in an immediate failure where the cause is obvious. Dereferencing a non-NULL pointer that can not be safely dereferenced is extremely likely to result in corrupt data and/or a corrupt heap, laying a land mine or twelve that will cause later failures in what can be totally unrelated code.

You code will have bugs. There's nothing but downside in using a code construct that makes those bugs more likely to occur along with making them harder to find when they do occur.

| improve this answer | |
  • 4
    There is a crucial difference between "no data" (yet) and "data of length zero" in many cases. Not that malloc(0) helps in either case. – Deduplicator Jun 7 at 17:02
  • @Deduplicator True, but in a case like that you have to have to pass additional information such as data length that can't be conveyed simply by NULL/non-NULL state. – Andrew Henle Jun 7 at 17:05
2

Note that since C17/18 a subtle addition occurred:

If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is returned to indicate an error, 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. § 7.22.3 1

Now when malloc(0) returns NULL, that indicated an error1 such as out-of-memory or perhaps code reached a maximum number of allocations or ...


The only value I see with the below is determining, in this case via debugger as a weak test, to find if any memory or allocation is available.

char **v = malloc(0);
while ((r = strtok(s, " ")) != NULL) {
  char **vv = realloc(v, (n+1)*sizeof(*vv));

is it a good convention?

No, simple is better.

char **v = NULL;

1 C specification is fuzzy if a size of 0 in itself an error. So this new added to indicate an error I find less helpful.

In general, I try to avoid *alloc(0) as C historically lacks clarity with 0 and so I simply assign NULL with size 0 to avoid any ambiguity.

| improve this answer | |
  • "A request for zero bytes always fails." still remains a valid choice for implementers. The only sticky point might be realloc(). – Deduplicator Jun 18 at 0:17
  • @Deduplicator True. Any source for the quote? – chux - Reinstate Monica Jun 18 at 1:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.