Почему я получаю утечку памяти? - PullRequest
0 голосов
/ 17 сентября 2018

Рассмотрим следующий фрагмент кода: #include #include

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);
}

Почему вышеуказанная программа вызывает утечку памяти?Как мне избежать этого?

Считается, что в "str = NULL;" произошла ошибка.Почему?

Журнал Valgrind:

==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)

1 Ответ

0 голосов
/ 02 ноября 2018

free(str); освобождает пространство, на которое указывает str, где str - пространство, полученное malloc. Поскольку строка str = NULL; происходит до того, как free, free пытается освободить позицию памяти в местоположении 0. По определению в стандарте C это ничего не делает. Обычно после удаления указатель устанавливается на 0, чтобы при случайной попытке удалить его снова ничего не происходило.

Чтобы исправить ваш код, вам просто нужно поменять местами строки str = NULL; и free(str);

...