8

Possible Duplicates:
what does malloc(0) return ?
what’s the point in malloc(0)?

Why does malloc(0) return valid memory address ? What's the use ?

Community
  • 1
  • 1

5 Answers5

8

If the size of the space requested is 0, the behavior is implementation-defined: the value returned shall be either a null pointer or a unique pointer.

Source: malloc at The Open Group

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
tur1ng
  • 3,139
  • 5
  • 24
  • 31
2

I guess the address is valid only if you want to use 0 bytes from it. The use would probably be not having to specially treat cases like:

char * foo = malloc(size);
// do something with foo
free(foo);
che
  • 12,097
  • 7
  • 42
  • 71
  • Well yes, but you have to handle a NULL return value anyway and any decent programmer will have a coherent value of size at this point or after the malloc... – neuro Jun 24 '10 at 14:04
  • 1
    However, it is also safe to pass `NULL` to [`free`](http://pubs.opengroup.org/onlinepubs/009695399/functions/free.html). – Matthew Flaschen Jul 01 '12 at 01:05
2

It does not return a valid address.

The result of malloc(0) is implementation defined and therefore unreliable.

Some compiler implementations will cause it to return a NULL pointer, others may return some other value (but it still can't/shouldn't be used to access memory).

The memory cannot be used, (however it may require free()ing).

Fish
  • 459
  • 2
  • 6
  • You are right that it is implementation dependant but malloc(0) returns either NULL or a VALID address (meaning that you can call free on it without a segfault). So it returns a valid address. But you are right to say that you shouldn't use it. Anyway as any decent programmer will have code correctly checking size, it is kind of pointless debate ;) I agree with che saying it can save some more specific checks ... – neuro Jun 24 '10 at 14:11
2

It isn't mandated in C (but it is mandated for new in C++). There are cases where objects have no state (and so have a null size) but their identity is important. In such case having an allocator which returns valid and different objects for a size of 0 is needed if you need to allocate them dynamically.

AProgrammer
  • 51,233
  • 8
  • 91
  • 143
  • +1 for the comment on object state. A pity such things are implementation dependant ... – neuro Jun 25 '10 at 17:12
  • As you said, since this is implementation-dependent, it's useless. If you want to use such an ugly method of identifying distinct zero-size objects, just pass `MIN(1,size)` to `malloc` and pat yourself on the back for wasting at least 16 bytes per identity. – R.. GitHub STOP HELPING ICE Dec 18 '10 at 12:47
0

I cannot imagine a use for that, but, it is probably the result of malloc's design: if it's easier to support it than to not support, it should be supported.

Just as it's okay to take asin(4), and it returns a complex number... oops no it doesn't...

Pavel Radzivilovsky
  • 18,794
  • 5
  • 57
  • 67