How to deallocate memory without using free() in C?

Share Your Love

Here is the question around dynamic memory allocation for deallocate memory without using free() in C.

Generally, in C free() function is used to deallocate memory, but here we deallocate without the help of free().

Standard library function realloc() used to previously deallocate memory to allocate it.

Below is function declaration of “realloc()” from “stdlib.h”.

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

If there “size” is zero, then the call to realloc() is equivalent to “free(ptr)”. If ptr is Null and size is non-zero then call to realloc() is equivalent to malloc(size).

Let us check with an easy example.

/* code with memory leak */
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
	int *ptr = (int*)malloc(10);

	return 0;
}

 Inside the valgrind tool, it shows the leaked summary. The memory leak of 10 bytes, which is highlighted in red colour.

[lingaraj@ubuntu]$ valgrind –leak-check=full ./free
  ==1238== LEAK SUMMARY:
  ==1238==    definitely lost: 10 bytes in 1 blocks.
  ==1238==      possibly lost: 0 bytes in 0 blocks.
  ==1238==    still reachable: 0 bytes in 0 blocks.
  ==1238==         suppressed: 0 bytes in 0 blocks.

Now modify the above code,

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

int main(void)
{
	int *ptr = (int*) malloc(10);

	/* we are calling realloc with size = 0 */
	realloc(ptr, 0);
	

	return 0;
}

Now check Valgrind’s Output. Now, memory leaks are possible, highlighted in red colour.

 [lingaraj@ubuntu]$ valgrind –leak-check=full ./a.out
  ==1435== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 11 from 1)
  ==1435== malloc/free: in use at exit: 0 bytes in 0 blocks.
  ==1435== malloc/free: 1 allocs, 1 frees, 10 bytes allocated.
  ==1435== For counts of detected errors, rerun with: -v
  ==1435== All heap blocks were freed — no leaks are possible.
  [lingaraj@ubuntu]$

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Share Your Love
Avatar photo
Lingaraj Senapati

Hey There! I am Lingaraj Senapati, the Founder of lingarajtechhub.com My skills are Freelance, Web Developer & Designer, Corporate Trainer, Digital Marketer & Youtuber.

Articles: 429

Newsletter Updates

Enter your email address below to subscribe to our newsletter