Select Page

Dynamic Memory Allocation in C

by 19.03.2023Dynamic Memory Management in C

There are 3 important basic step that are used for dynamic memory allocation:

  1. Use a malloc to allocate memory.
  2. Use this allocated memory to support the application.
  3. Deallocate the memory using free function.
#include <stdio.h>
#include <stdlib.h> //used for malloc

int	main(void)
{
	int	*ptr;

	ptr = (int *)malloc(sizeof(int));
	*ptr = 2;
	printf("value of ptr: %d\n", *ptr);
	free(ptr);
	return (0);
}
Terminal> gcc DynamicMemoryAlloc.c
Terminal> ./a.out
value of ptr: 2

Terminal> valgrind ./a.out

==32902== Memcheck, a memory error detector
==32902== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==32902== Using Valgrind-3.18.1 and LibVEX; rerun with -h for copyright info
==32902== Command: ./a.out
==32902== 
value of ptr: 2
==32902== 
==32902== HEAP SUMMARY:
==32902==     in use at exit: 0 bytes in 0 blocks
==32902==   total heap usage: 2 allocs, 2 frees, 1,028 bytes allocated
==32902== 
==32902== All heap blocks were freed -- no leaks are possible
==32902== 
==32902== For lists of detected and suppressed errors, rerun with: -s
==32902== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

In the example above, we allocate the memory for an integer, then we assign the value 2 to allocated memory using the pointer dereferencing and in the end we release the memory using the free function. As seen we use also valgrind to check memory leaks and heap usage. Valgrind will be explained later.

Below you can see the graphical illustration of our example:

Free function

Every time that malloc or similar function is called, a corresponding free function must be called after the the application of allocated memory is done to avoid memory leaks. After the memory is free, it should not be accessed again. Accessing the freed memory accidentally is called “Dangling Pointer”. This will be explained later. A common practice is to assign NULL to a freed pointer. This will be also discussed later.

SOURCES:
[1] Understanding and Using C Pointers by Richard Reese (O’Reilly). Copyright 2013 Richard Reese, Ph.D. 978-1-449-34418-4