tags:

views:

160

answers:

5

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 ?

+2  A: 

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
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
+7  A: 

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: link text

tur1ng
+1 for the link
neuro
+1  A: 

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
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
A: 

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
You need casin for the result to be a complex.
Pete Kirkham
What !? C does not support a complex type out of the box ? What a pity :-)
neuro
@neuro You will laugh but C does support complex out of the box. C99 requires compilers to implement 'complex' as a native type.
Pavel Radzivilovsky
@Pavel : Ahah. Too long a time I have not coded in C :-) If I wait long enough, I will have introspection ;-)
neuro
+1  A: 

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
+1 for the comment on object state. A pity such things are implementation dependant ...
neuro