What's the point of malloc(0)?

后端 未结 17 1774
庸人自扰
庸人自扰 2020-11-22 15:40

I just saw this code:

artist = (char *) malloc(0);

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

17条回答
  •  -上瘾入骨i
    2020-11-22 15: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.

提交回复
热议问题