C Dynamic memory allocation | Explanation | Examples

C Dynamic memory allocation – Learn what is dynamic allocation and how to create memory dynamically in C programs using C library functions malloc, calloc, realloc and free with examples. Explanation and notes if any has been provided for all functions.

Dynamic memory allocation means to allocate memory in the program at the time of execution of the program. In C program, dynamic memory is allocated from the heap memory at run time. Note that static memory allocation is done from Stack, a section from memory, at compile time itself.

What functions are used to allocate memory dynamically in C programs?

Dynamic memory allocation in C programs are done using standard C library functions –  malloc (), calloc(), realloc() and free() functions.  You can find these functions in “stdlib.h” header file. Hence, if we need use this function then need to include the header file in C program.

malloc, calloc and reaalloc functions are used for memory allocation dynamically and free function is used to free the memory block.

NOTE:

  • In C programming, the programmer is responsible to deallocate the memory from heap using free function explicitly. If programmer does not free the memory then program will hold the memory unnecessarily from heap and this memory cannot be used by other programs. Memory from heap cannot be freed automatically as static memory from stack get freed automatically once the variable holding the static memory address goes out of scope.
  • When we allocate the memory dynamically using malloc or calloc etc., the returned address by them is always stored in a pointer.

C Dynamic memory allocation using library functions

C MALLOC FUNCTION

C Syntax :  –  void *malloc(size_t size):

malloc function is used to allocate memory from heap at run time.  Malloc receives the requested size of bytes as an argument and allocate chunk of memory (memory block from heap area) of requested size and returns the starting address keeping in a void pointer. void word in the void pointer indicates that this pointer does not know the data type. In simple words, malloc does not know what data type the requested user (part of the program) is going to store. So, just it allocates the required memory chunk and return it. User is responsible to typecast it to the pointer type e.g. int pointer or float pointer etc. whatever data types he wants to store. e.g.

int *ptr = (int *)malloc(Required size); or float *ptr = (float *)malloc(Required size); etc.

Some important points about malloc:

  • Allocated memory chunk by malloc function contains garbage value and it can be initialized with any value you wish using memset() function explicitly. e.g. memset( pointer, value you want, size )
  • malloc function returns null pointer if dynamic memory allocation fails, means if no memory from heap is available.

NOTE:  If memory allocation fail then we should stop furher processing in the program or else program will crash because of memory access violation. If we read write something on the memory that does not exist, then memory violation occurs.

MALLOC PROGRAM EXAMPLE

/*----------------------------------------------------
* malloc() function in C program examples
*/
#include <stdio.h>

int main()
{
	//Create a pointer to store address returned
	//by malloc
	int *ptr = NULL;

	/*------Memory allocation and validation-----------*/

	/*Dynamically allocate memory for
	* one integer value. Size we need to give to 
	* malloc function is using sizeof(int). sizeof(it)
	* will give size of 1 integer
	*/


	//Typecast to int as malloc returns void pointer and 
	//we want to store int data type in it
	ptr = (int *)malloc(sizeof(int));

	//Check if malloc has allocated memory chunk successfully.
	//malloc retruns NULL on memory allocation failure.
	if (ptr == NULL)
	{
		printf("ERROR: memory allocatin fail\n");

		//If memory allocation fails then return from here
		//and stop process processing or else program will
		//crash e.g. if we try to read write value on it.
		return 1;
	}

	/*------Read write on allocated memory-------------*/

	//Write some value on memory chunk allocated.
	*ptr = 12;

	// Read value from memory chunk
	printf("%d\n", *ptr);


	/*------     Memory de-allocation      -------------*/
	//Free allocated memory explicitly as
	//it memory will not be freed automatically.
	free(ptr);

	return 0;
}

Output: 12

C CALLOC FUNCTION

C Syntax :  – void* calloc (size_t num, size_t size);

Calloc() functions receives two arguments i.e. number of elements and size of 1 element. Calloc function also returns a void pointer of allocated memory e.g. ptr = (int*) calloc (i,sizeof(int)); // i is the number of elements of int type.  The memory allocated by calloc is by default is initialized by zero.

CALLOC PROGRAM EXAMPLE

/*----------------------------------------------------
* calloc() function in C program examples
*/
#include <stdio.h>
int main ()
{
	int i = 0;
	int * ptr = NULL;  

	/*------Memory allocation and validation-----------*/
	//Allocate memory for 5 integers.
	//Pass 2 arguments i.e. number of elements and size of 
	// one element
	ptr = (int*) calloc (5,sizeof(int));
	if (ptr == NULL)
	{
		printf("ERROR: memory allocation fail\n");			
		return 1;
	}

	/*------Read write on allocated memory-------------*/

	printf("By default values: ");
	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("Entered values:");
	for (i = 0; i < 5; i++) {
		printf("%d ", ptr[i]);
	}  

	/*------     Memory deallocation      -------------*/
	free (ptr);

	return 0;
}

OUTPUT:

By default values: 0 0 0 0 0
Entered values:0 1 2 3 4

C REALLOC FUNCTION

C Syntax :  – void *realloc( void *ptr, size_t new_size );

Realloc function is used to extend the existing allocated memory by malloc() or calloc() functions with new size. It receives two argument, that pointer to existing memory done by malloc or calloc, and the new size for new memory allocation.

In fact, realloc () function allocate new memory chunk of given new size and assign the address to received pointer. Copy the content from old memory pointed by ptr to new memory chunk and deallocate the old memory internally.

REALLOC PROGRAM EXAMPLE

In this program, we will allocate memory dynamically for 1 integer value using malloc function and write a number, say 5 on it. on reading it will output 5.

Further, we will expand memory for 4 more integer elements using realloc and write 4 elements i.e. 1,2,3 and 4 on extended new memory. note that we are not touching exiting elements 5. After using realloc, the output will be 5,41,2,3,4

/*----------------------------------------------------
* ralloc() function in C program examples
*/
#include <stdio.h>

int main()
{
	int *ptr = NULL;
	int i =0;

	/*----Allocate memory for 1 integer using malloc---*/
	//memory allocation for 1 integer. 
	ptr = (int *)malloc(sizeof(int));
	//Write value at the memory location
	*ptr = 5;
	// Read value from memory
	printf("Existing value:%d\n", *ptr);

	/*---Extend memory for more integers using realloc--*/

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

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

	// Read values from new memory allocation
	//It should show numbers 5,2,3,4,1
	printf("Expanded values:");
	for (i = 0; i < 5; i++) {
		printf("%d", ptr[i]);
	}

	//Free allocated memory
	free(ptr);

	return 0;
}

OUTPUT:

Existing value:5
Expanded values:51234

C FREE FUNCTION

C Syntax :  – void free (void* ptr);

free function de-allocate memory previously allocated by dynamic functions malloc(), calloc() or realloc() and returns memory to operating system, so that other programs can use the free memory. free() function receives the pointer of previously allocated memory for memory de-allocation. Example has been already provided in the above program examples.

DOUBTS

So, for you understand what dynamic memory allocation is and what functions are used to allocate memory in the  C program dynamically or at run time and more. Read more on some doubt related to dynamic allocation.

Doubt: void free (void* ptr);  function receives only pointer means base or starting address and we does not pass the size of the memory block, then how does free know that what size of memory it has to free?

This concept is little bit tricky but simple. malloc free functions implementation varies compiler to compiler. They can implement different mechanism to free allocated memory. e.g. it can be implemented by memory section marking mechanism or using extra bytes to store the size of memory besides requested memory by the user.

Marking Mechanism to free memory:

Internally, the free () function’s job is to marking allocated memory section as “false” or 0. After allocating the memory of required size malloc() function returns the address of allocated memory and mark that section as true or 1 in one of the table/structure.

So, function free (), just need to know the address and not size of the memory. Marking memory as false or 0 is known as de-allocation of memory.

Extra bytes allocation mechanism to free memory:

During dynamic memory allocation, a chunk of memory (extra bytes+ requested size) with contiguous extra bytes besides requested size by user will be allocated from the heap to store the size of request memory. And by adjusting the pointer, actual request size of memory will be return to the user.

When free (void* p) method get called, it just go to that address pointed by the pointer and read the size of allocated memory from extra bytes memory to be freed.

Related Posts