Explain malloc calloc realloc free in c with example

Answer includes malloc calloc realloc free in c with example

Answer:

Dynamic memory allocation in C language programming is the process of memory allocation from heap memory at run time. In other word, when memory is allocated from heap during program execution is called dynamic memory allocation.

Also note that, in dynamic memory allocation, memory get allocated from heap and not from stack.

How dynamic memory allocation in C is done?

Dynamic memory allocation in C programming can be done using standard library functions –  malloc(), calloc(), realloc() and free(). All these library functions are available in “stdlib.h” header file. Hence, we have to include this header in c program.

malloc(), calloc() and realloc ()  – perform memory allocation and free() function perform de-allocation. It is important to note that if we allocate memory dynamically then we must de-allocate it manually / explicitly using free () method. Because, dynamically allocated memory can’t be freed automatically like static memory allocation in C.

NOTE: Dynamic memory must be freed or else memory leak issues will occur.

Library functions’ important points with C program example:

malloc() function in C –  void *malloc(size_t size):

  • malloc function allocates memory from heap of requested size of bytes and returns a void pointer to first byte of allocated memory. We need to typecast void pointer to data type that we are requesting memory for allocation.
  • Allocated memory space by malloc() contains garbage value and it can be initialized with any value using memset() function explicitly.
  • malloc () function returns null pointer if memory allocation fails

malloc () function Program Example :

int main()
{
	int *ptr = NULL;
	//dynamically allocate memory for
	//one integer value. sizeof(int) will give
	//size of 1 integer

	//Typecast to int as malloc returns void pointer
	ptr = (int *)malloc(sizeof(int));

	if (ptr == NULL)
	{
		printf("ERROR: memory allocatin fail\n");
		//return from here and process further
		return 1;
	}

	//place value on memory created
	*ptr = 5;

	// Read value from memory and
	// display on console
	printf("%d\n", *ptr);

	//Free allocated memory
	free(ptr);

	return 0;
}

You may like to read interview question: malloc() function program example in C on multiple scenarios.

 

calloc() function in C – void* calloc (size_t num, size_t size);

  • Allocation memory block that is initialized by zero.
  • Calloc() functions receives number of elements and 1 element size. Calloc returns a void pointer of allocated memory e.g. ptr = (int*) calloc (i,sizeof(int)); // i is the number of elements of int type.

calloc () function C Program Example:

int main ()
{
  int i = 0;
  int * ptr = NULL;  
 
  //Allocate memory for 5 intergers
  ptr = (int*) calloc (5,sizeof(int));
  if (ptr == NULL)
  {
	  printf("ERROR: memory allocatin fail\n");			
	  return 1;
  }

  //Print value at memory. 
  //Since, calloc is zero initialized all
  //value shuld be 0;
  printf("By defaul, all values are: ");
  for (i = 0; i < 5; i++) {
	  printf("%d ", ptr[i]);
  }
	printf("\n");
  
  //Now, assign value from 0 to 4
  for (i = 0; i < 5; i++) {
		ptr[i] = i;
	}

  //Print value at memory.
  printf("After entered values:");
  for (i = 0; i < 5; i++) {
	  printf("%d ", ptr[i]);
  }  
  free (ptr);

  return 0;
}

OUTPUT:

By defaul, all values are: 0 0 0 0 0
After entered values:0 1 2 3 4

realloc() function in C – void *realloc( void *ptr, size_t new_size );

  • Re- allocate the allocated memory by malloc() and calloc() functions that is not freed with new size.
  • In fact, realloc () function copy the content from old memory pointed by ptr to new memory and deallocate the old memory internally.

realloc () function C Program Example :

int main()
{
	int *ptr = NULL;
	int i =0;
	//dynamic allocation for 1 integer value. 
	ptr = (int *)malloc(sizeof(int));
	//place value on memory created
	*ptr = 5;
	// Read value from memory
	printf("%d\n", *ptr);

	//Expand existing memory for 4 more integers
	// size of 1 integer* 5
	// Reallocate memory
   ptr = (int *) realloc(ptr, sizeof(int)*5);

   //place 4 numbers on expanded memory
   // 1 2 3 4
   	for (i = 1; i < 5; i++) {
		ptr[i] = i;
	}

   // Read value from re-allocated memory
	//It should show numbers 5,1,2,3,4
   	for (i = 1; i < 5; i++) {
		printf("%d\n", ptr[i]);
	}
	
	//Free allocated memory
	free(ptr);

	return 0;
}

free() – void free (void* ptr);

  • Deallocate memory previously allocated by functions malloc(), calloc() or realloc() and returns memory to operating system, so, other program can use free memory.
  • free() function receives the pointer of previously allocated memory for memory deallocation.

Dynamic memory allocation in c programming is frequently asked interview question. But, there is another tricky question, especially relevant to this question we must focus on, that how does free() function know how much memory to free as we are passing only pointer (address) to free function?

Related Posts