behaviour of malloc(0)
c, pointers
Solution
It is implementation defined what `malloc()` will return but it is undefined behavior to use that pointer. And Undefined behavior means that anything can happen literally from program working without glitch to a crash, all safe bets are off.
C99 Standard:
7.22.3 Memory management functions Para 1:
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.
Problem
``` int main() { char *p; p = (char* ) malloc(sizeof(char) * 0); printf("Hello Enter the data without spaces :\n"); scanf("%s",p); printf("The entered string is %s\n",p); //puts(p); } ``` On compiling the above code and running it , the program is able to read the string even though we assigned a 0 byte memory to the pointer p . What actually happens in the statement `p = (char* ) malloc(0)` ?