calloc and realloc in C

Another memory allocating tool is the C standard library function calloc(). Like the malloc() function, the calloc() function attempts to grab contiguous segments of memory from the heap. The calloc() function takes two arguments: the first determines the number of memory segments needed and the second is the size of the data type.

A basic implementation of the calloc() function

#include <stdio.h>
#include <stdlib.h>
 int *numbers;
 numbers = (int *) calloc(10, sizeof(int));
 if ( numbers == NULL )
 return; // return if calloc is not successful 

The main benefit of using calloc() rather than malloc() is calloc()’s ability to initialize each memory segment allocated. This is an important feature because malloc() requires that the programmer be responsible for initializing memory before using it

Both malloc() and calloc() appear to be dynamic in memory allocation, and they are to some degree, yet they fall somewhat short in their ability to expand memory originally allocated. For example, say you allocated five integer memory segments and filled them with data. Later, the program requires that you add five more memory segments to the original block allocated by malloc() while preserving the original contents. This is an interesting dilemma. You could, of course, allocate more memory using a separate pointer, but that would not allow you to treat both memory blocks as a contiguous memory area and, therefore, would prevent you from accessing all memory segments as a single array. Fortunately, the realloc() function provides a way to expand contiguous blocks of memory while preserving the original contents

the realloc() function takes two arguments for parameters and returns a pointer as output

newPointer = realloc(oldPointer, 10 * sizeof(int));

realloc()’s first argument takes the original pointer set by malloc() or calloc(). The second argument describes the total amount of memory you want to allocate

 int *number;
 int *newNumber;
 int x;
 number = malloc(sizeof(int) * 5);
 if ( number == NULL ) {
 printf("\nOut of memory!\n");
 } // end if
 printf("\nOriginal memory:\n");
 for ( x = 0; x < 5; x++ ) {
 number[x] = x * 100;
 printf("number[%d] = %d\n", x, number[x]);
} // end for loop
 newNumber = realloc(number, 10 * sizeof(int)); 
 if ( newNumber == NULL ) {
 printf("\nOut of memory!\n");
 number = newNumber;
 //intialize new memory only
 for ( x = 5; x < 10; x++ )
 number[x] = x * 100;
 printf("\nExpanded memory:\n");
 for ( x = 0; x < 10; x++ )
 printf("number[%d] = %d\n", x, number[x]);
 //free memory

Leave a Comment