If we pass null pointer in malloc or calloc function, What will be the result?

Questions by parvesh devi

Showing Answers 1 - 4 of 4 Answers

Lohith Nayak

  • Jun 8th, 2007
 

calloc(NULL, 2) = malloc(2).

calloc(NULL,0) = malloc(0).

  Was this answer useful?  Yes

kannan987

  • Jun 13th, 2008
 

It Allocates Some memory..

 #include "test.h"


int main(void)
{
    int *p = NULL;
 int *c =(int*)malloc(sizeof(p));
 printf("%0x",&c);
 return 0;

}

o/p : return some memory address

kannan987

  • Jun 13th, 2008
 

test.h is nothing but in my pgm..

simply include all header files..

<----test.h--->

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>

  Was this answer useful?  Yes

kbjarnason

  • Jul 1st, 2010
 

You don't pass null pointers to malloc or calloc.  You can pass them to realloc.

Perhaps you mean what would happen if you did this:

#include <stdlib.h>

int main(void)
{
   char *ptr = NULL;

    ptr = malloc(100);

    if ( ptr )
      free( ptr );

   return 0;
}


In this case, the fact that ptr is NULL when you call malloc is really irrelevant, since all you're doing is assigning malloc's return value to ptr anyhow.


Side note: in C, do *not* cast the return value of malloc.  It returns a void pointer, which is type compatible with anything you're going to be meaningfully assigning to, and the cast can cause the compiler to overlook a potentially disastrous bug.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions