我在C语言中声明了一个简单的字符串:
#include <stdio.h>
int main()
{
char *t1 = "hello";
return 0;
}
你可以看到,我的代码中没有任何 free
。我使用以下命令通过 valgrind
进行了检查:
valgrind --tool=memcheck --track-origins=yes --leak-check=yes --show-reachable=yes -v --track-fds=yes ./test
它显示:
==4329== HEAP SUMMARY:
==4329== in use at exit: 0 bytes in 0 blocks
==4329== total heap usage: 0 allocs, 0 frees, 0 bytes allocated
==4329==
==4329== All heap blocks were freed -- no leaks are possible
==4329==
==4329== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)
为什么会这样呢?我的意思是,我使用了一个指针
*T
,但没有在任何地方释放它。我以为这应该导致内存泄漏。为什么不会出现内存泄漏?
malloc()
,那么你就不需要释放任何东西。 - user2422531