Why does malloc(0) allocated memory? | SoloLearn: Learn to code for FREE!

+1

Why does malloc(0) allocated memory?

Ptr=(int*)malloc(0); *ptr=34; printf("ptr=%d",*ptr); Output: ptr=34

2/19/2020 5:42:39 AM

Vidya Patil

4 Answers

New Answer

+5

malloc(0) does not allocate any memory. [EDITED: it can sometimes allocate memory, see my next answer] The return value of malloc (0) is implementation specific: it can return NULL or a valid pointer (some unique value) as in your case but memory is not allocated!!! In any case the pointer returned by malloc(0) should not be dereferenced!!!

+3

andriy kan then, if the pointer should not be used, why does malloc(0) return a valid pointer instead of a NULL pointer?

+3

@Théophile because the standard allows it. I was wrong that malloc(0) does not allocate any memory. Sometimes it may allocate, but it is implementation specific and that pointer must not be dereferenced. according to standard the behavior of malloc(0) 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. The result can be NULL, some unique value (memory is not allocated and is not freed when that unique value is used), or valid pointer with memory allocation (as standard allows it). malloc always returns NULL if it is failed to allocate memory. But if you call malloc with a variable that contains zero value as the result of some computation this is not memory allocation failure, so implementaion can use other values (to distinguish from memory allocation failure) as result of malloc(0) , but again, that pointer should not be dereferenced.

+2

Théophile The specification says it's implementation defined and the pointer should not be dereferenced. The pointer must be freed if it is not NULL. C runs on wide variety of devices. May be the standards gave enough freedom to compiler implementers to exploit some specific device architecture. Or probably it the same type of thing as zero sized arrays allowed in old C (char arr[0];). Just guessing not sure though :)