Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

behaviour of malloc(0)

Tags:

c

pointers

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) ?

like image 748
svKris Avatar asked May 21 '12 11:05

svKris


People also ask

Can I malloc size of 0?

DESCRIPTION top. The malloc() function allocates size bytes and returns a pointer to the allocated memory. The memory is not initialized. If size is 0, then malloc() returns either NULL, or a unique pointer value that can later be successfully passed to free().

Do you have to free malloc 0?

Yes, free(malloc(0)) is guaranteed to work.

Does calloc initialize to 0 or NULL?

calloc returns a pointer to the first element of the allocated elements. If memory cannot be allocated, calloc returns NULL . If the allocation is successful, calloc initializes all bits to 0.

What does malloc initialize to?

Initialization. malloc() allocates a memory block of given size (in bytes) and returns a pointer to the beginning of the block. malloc() doesn't initialize the allocated memory.


1 Answers

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.

like image 149
Alok Save Avatar answered Oct 19 '22 11:10

Alok Save