Why does malloc(0) allocated memory? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why does malloc(0) allocated memory?

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

19th Feb 2020, 5:42 AM
Vidya Patil
Vidya Patil - avatar
3 Answers
+ 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!!!
19th Feb 2020, 7:04 AM
andriy kan
andriy kan - avatar
+ 3
andriy kan then, if the pointer should not be used, why does malloc(0) return a valid pointer instead of a NULL pointer?
19th Feb 2020, 7:08 AM
Théophile
Théophile - avatar
+ 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.
19th Feb 2020, 8:44 AM
andriy kan
andriy kan - avatar