Thursday, August 03, 2006

Difference between malloc and calloc

1. malloc() doesnot initialize the memory allocated, while calloc() initializes the allocated memory to ZERO.

2. malloc() takes a single argument(memory required in bytes), while calloc() needs 2 arguments(number of variables to allocate memory, size in bytes of a single variable). (malloc does byte level and calloc does block level allocation)

Syntax: input i

char * buffer;
buffer = (char*) malloc (i+1);
int * pData;
pData = (int*) calloc (i,sizeof(int));

calloc(m, n) is essentially equivalent to

p = malloc (m * n);
memset (p, 0, m * n);

void * realloc ( void * ptr, size_t size );

ptr: Pointer to a memory block previously allocated with malloc, calloc or realloc to be reallocated.
If this is NULL, a new block is allocated and a pointer to it is returned by the function. so pointer = realloc (0, sizeof(int)) is legal.

size: New size for the memory block, in bytes.
If it is 0 and ptr points to an existing block of memory, the memory block ointed by ptr is deallocated and a NULL pointer is returned. [update: 4/29/08]

No comments:

Post a Comment