我在 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
但没有在任何地方释放它。我认为它应该给我内存泄漏。为什么不?
最佳答案
您没有分配内存。您正在可执行文件的数据段中创建一个常量字符串,并分配一个指向该内存位置的指针。释放它(或写入该内存位置)将是一个错误(未定义的行为)。
关于c - 为什么 char *T = "hello";不给内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19877915/