메모리 유출이 발생하는 이유가 뭔가요??
조회수 1356회
아래 코드를 빌드해서, valgrind 를 사용해서 확인해보니깐 memory leak가 발생하는데..
이유가 뭔가요?
" str = NULL;" 이거 떄문에 문제가 발생하는것 같은데..
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)
-
(•́ ✖ •̀)
알 수 없는 사용자
1 답변
-
free 전에 NULL을 대입하면... str이 NULL 포인터를 가르키고 있기 때문에 기존에 할당받은 15바이트가 해제되는 것이 아니라 엉뚱하게 NULL주소값에 가서 해제를 시도하게 됩니다.
이 경우에 할당 받은 heap 메모리 영역의 15바이트는 가르키는 포인터가 없기 때문에 해당 주소로 진입할 수 없게 되고(dangling) 해제 할 방법이 사라지게 되죠.
이는 전형적인 메모리 누수 상황입니다.
free() 후에 NULL을 assign하는 것이 일반적입니다.
댓글 입력