What is the reason for the memory leak?

Asked 2 years ago, Updated 2 years ago, 113 views

I built the code below and checked it using the valgrind, and the memory leak occurred.

What's the reason?

"str = NULL;" I think that's what's causing the problem.

int main () {
   char *str;

   /* /* Initial memory allocation */
   str = (char *) malloc(15);
   strcpy(str, "tutorialspoint");
   printf("String = %s,  Address = %u\n", str, str);
   str = NULL;

   free(str);

   return(0);
}

valgrind log:

==4143== Memcheck, a memory error detector
==4143== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==4143== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==4143== Command: ./a.out
==4143== 
String = tutorialspoint,  Address = 86097984
==4143== 
==4143== HEAP SUMMARY:
==4143==     in use at exit: 15 bytes in 1 blocks
==4143==   total heap usage: 2 allocs, 1 frees, 1,039 bytes allocated
==4143== 
==4143== 15 bytes in 1 blocks are definitely lost in loss record 1 of 1
==4143==    at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==4143==    by 0x1086EB: main (in /home/stack/a.out)
==4143== 
==4143== LEAK SUMMARY:
==4143==    definitely lost: 15 bytes in 1 blocks
==4143==    indirectly lost: 0 bytes in 0 blocks
==4143==      possibly lost: 0 bytes in 0 blocks
==4143==    still reachable: 0 bytes in 0 blocks
==4143==         suppressed: 0 bytes in 0 blocks
==4143== 
==4143== For counts of detected and suppressed errors, rerun with: -v
==4143== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 0 from 0)

memory

2022-09-22 10:45

1 Answers

If you put NULL before free... Since str points to the NULL pointer, the previously allocated 15 bytes are not released, but rather go to the NULL address value and try to release it.

In this case, 15 bytes of the allocated heap memory area will not be able to enter the address because there is no pointing pointer, and the way to unlock it will disappear.

This is a typical memory leak situation.

It is common to assign NULL after free().


2022-09-22 10:45

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.