我实现了一个返回字符串的函数。它使用整数作为参数(age),并返回格式化的字符串。
一切运行良好,除了我有一些疯狂的内存泄漏的事实。我知道strdup()是造成这种情况的原因,但是我试图研究一些修复措施但无济于事。
我的代码是:
const char * returnName(int age) {
char string[30];
sprintf( string, "You are %d years old", age);
return strdup(string);
}
Run Code Online (Sandbox Code Playgroud)
Valgrind的输出是:
==15414== LEAK SUMMARY:
==15414== definitely lost: 6,192 bytes in 516 blocks
==15414== indirectly lost: 0 bytes in 0 blocks
==15414== possibly lost: 0 bytes in 0 blocks
==15414== still reachable: 0 bytes in 0 blocks
==15414== suppressed: 0 bytes in 0 blocks
Run Code Online (Sandbox Code Playgroud)
非常感谢您对解决此内存泄漏问题的任何帮助。
strdup()本质上等效于
char* dup = malloc(strlen(original) + 1);
strcpy(dup, original);
Run Code Online (Sandbox Code Playgroud)
因此,您需要记住free()在使用完字符串后再调用。
const char* name = returnName(20);
/* do stuff with name */
free((void*)name);
Run Code Online (Sandbox Code Playgroud)
如果您不致电free(),那么valgrind当然会报告泄漏。