Select Page

Using the function realloc in C

by 03.04.2023Dynamic Memory Management in C

When you need to increase or decrease the amount of allocated memory to a pointer you can use function realloc. Bellow you can see the prototype of this function.

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

Realloc function returns a pointer to a block of a memory. It takes two arguments. The first argument is a pointer to the original block of memory. The second argument is requested size. The return value is the address to the reallocated memory.

If the requested size of reallocated memory is less than the original one, the memory is returned to the heap. It is important to know that there is no guarantee that the excess of memory will be cleared. If the requested size is greater than the original one, the memory will be allocated from the heap to the region immediately following the current location of original block of memory, if possible. If not possible, the requested memory is allocated in different region and the old memory is copied.

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

int	main(void)
{
	char	*str1;
	char	*str2;

	str1 = (char *) malloc(8);
	strcpy(str1, "1234567");
	printf("str1 %p [%s]\n", str1, str1);
	str2 = realloc(str1, 6);
	printf("str1 %p [%s]\n", str1, str1);
	printf("str2 %p [%s]\n", str2, str2);
	free(str2);
	return (0);
}

The result of this program would be:

Terminal> gcc realloc.c
Terminal> ./a.out
str1 0x55efc85552a0 [1234567]
str1 0x55efc85552a0 [1234567]
str2 0x55efc85552a0 [1234567]

==9905== HEAP SUMMARY:
==9905==     in use at exit: 0 bytes in 0 blocks
==9905==   total heap usage: 3 allocs, 3 frees, 1,038 bytes allocated
==9905== 
==9905== All heap blocks were freed -- no leaks are possible
==9905== 
==9905== For lists of detected and suppressed errors, rerun with: -s
==9905== ERROR SUMMARY: 23 errors from 6 contexts (suppressed: 0 from 0)

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