Dynamic Memory Allocation in C

In dynamic memory management memory will be allocate at run time via a group of functions in the C standard library, namely malloc, realloc, calloc and free. This is also known as heap memory.

malloc:

The malloc() function dynamically allocates memory when required. This function allocates ‘size’ byte of memory and returns a pointer to the first byte or NULL if there is some kind of error.


void * malloc (size_t size);

malloc allocates memory in bytes.malloc() does not initialize the memory allocated.

int *ptr = malloc(sizeof(int) * 10); // allocates 10 ints!

calloc:

void *calloc(size_t nvar,size_t size)

calloc allocates memory in blocks. calloc initializes the allocated memory to zero. calloc takes two arguments, number of variables to be allocated and size of each variable.

int num;
int *ptr = (int*)calloc(num, sizeof(int));

realloc:

The realloc() function changes the size of a block of memory that was previously allocated with malloc() or calloc(). The function prototype is

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

The ptr argument is a pointer to the original block of memory. The new size, in bytes, is specified bysize.
There are several possible outcomes with realloc():

  • If sufficient space exists to expand the memory block pointed to by ptr, the additional memory is allocated and the function returns ptr.
  • If sufficient space does not exist to expand the current block in its current location, a new block of the size for size is allocated, and existing data is copied from the old block to the beginning of the new block. The old block is freed, and the function returns a pointer to the new block.
  • If the ptr argument is NULL, the function acts like malloc(), allocating a block of size bytes and returning a pointer to it.
  • If the argument size is 0, the memory that ptr points to is freed, and the function returns NULL.
  • If memory is insufficient for the reallocation (either expanding the old block or allocating a new one), the function returns NULL, and the original block is unchanged.
free:

When you allocate memory with either malloc() or calloc(), it is taken from the dynamic memory pool that is available to your program. This pool is sometimes called the heap, and it is finite. When your program finishes using a particular block of dynamically allocated memory, you should deallocate, or free, the memory to make it available for future use. To free memory that was allocated dynamically, use free(). 


void free(void *ptr); 

The free() function releases the memory pointed to by ptr. This memory must have been allocated with malloc(), calloc(), or realloc(). If ptr is NULL, free() does nothing.

No comments:

Post a Comment