Q:

What is the return value of malloc (0)?

0

What is the return value of malloc (0)?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer:

If the size of the requested space is zero, the behavior will be implementation-defined. The return value of the malloc could be a null pointer or it shows the behavior like that size is some nonzero value. So you must never use the malloc(0) in your C program.

Let see an example C program, where I am allocating memory using the malloc with size 0

#include<stdio.h>
#include<stdlib.h>
int main (void)
{
    int *piBuffer = NULL;
    //allocating memory using
    //the malloc with size 0.
    piBuffer = malloc(0);
    //make sure piBuffer is valid or not
    if (piBuffer == NULL)
    {
        // allocation failed, exit from the program
        fprintf(stderr, "Out of memory!\n");
        exit(1);
    }
    *piBuffer = 10;
    printf("%d\n",*piBuffer);
    free(piBuffer);
    return 0;
}

Output: Implementation-dependent.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

What is the memory leak in C?... >>
<< What is static memory allocation and dynamic memor...