我有一个函数可以在字符串中添加一个字符:
void AddChToString(char **str,char ch){
int len=(*str)?strlen(*str):0;
(*str)=realloc(*str, len+2);
(*str)[len]=ch;
(*str)[len+1]='\0';
}
仪器(在mac上)和Valgrind表示行:(* str)= realloc(* str,len + 2)正在泄漏内存。这是realloc的实现问题吗?或者我使用不当?
以下是Valgrind的输出:
==39230== 6 bytes in 1 blocks are definitely lost in loss record 1 of 7
==39230== at 0x100018B2D: realloc (vg_replace_malloc.c:525)
==39230== by 0x100002259: AddChToString (in ./OpenOtter)
==39230== by 0x10000477B: QueryMapFromString (in ./OpenOtter)
==39230== by 0x100684CD2: ???
==39230== by 0x100001FB0: RequestHandler (in ./OpenOtter)
==39230== by 0x100065535: _pthread_start (in /usr/lib/libSystem.B.dylib)
==39230== by 0x1000653E8: thread_start (in /usr/lib/libSystem.B.dylib)
==39230==
==39230== 9 bytes in 1 blocks are definitely lost in loss record 2 of 7
==39230== at 0x100018B2D: realloc (vg_replace_malloc.c:525)
==39230== by 0x100002259: AddChToString (in ./OpenOtter)
==39230== by 0x10000298E: ParseHTTPRequest (in ./OpenOtter)
==39230== by 0x100004151: OpenRoutesFile (in ./OpenOtter)
==39230== by 0x10000142B: main (in ./OpenOtter)
==39230==
==39230== 45 bytes in 5 blocks are definitely lost in loss record 3 of 7
==39230== at 0x100018B2D: realloc (vg_replace_malloc.c:525)
==39230== by 0x100002259: AddChToString (in ./OpenOtter)
==39230== by 0x10000298E: ParseHTTPRequest (in ./OpenOtter)
==39230== by 0x100001EB4: RequestHandler (in ./OpenOtter)
==39230== by 0x100065535: _pthread_start (in /usr/lib/libSystem.B.dylib)
==39230== by 0x1000653E8: thread_start (in /usr/lib/libSystem.B.dylib)
==39230==
==39230== LEAK SUMMARY:
==39230== definitely lost: 60 bytes in 7 blocks
==39230== indirectly lost: 0 bytes in 0 blocks
==39230== possibly lost: 0 bytes in 0 blocks
==39230== still reachable: 1,440 bytes in 4 blocks
==39230== suppressed: 0 bytes in 0 blocks
感谢。
答案 0 :(得分:8)
您的仪器是否表明存在实际泄漏或存在潜在泄漏?
如果 realloc()
失败,那么使用realloc()
会泄漏内存。在这种情况下,它将返回NULL
但不会释放原始块。所以你将失去指向该块的指针并且无法释放它(除非指针存储在别处)。
但这应该是罕见的(即,当你耗尽记忆力时)。
如果这是您的工具所抱怨的,您应该能够通过以下方式修复泄漏警告:
void AddChToString(char **str,char ch){
int len=(*str)?strlen(*str):0;
char* tmp = realloc(*str, len+2);
if (!tmp) {
// whatever error handling is appropriate
}
(*str)=tmp;
(*str)[len]=ch;
(*str)[len+1]='\0';
}
答案 1 :(得分:3)
调用realloc本身不会泄漏内存。您应该确保重新分配的字符串的内存在不再需要时免费释放。
答案 2 :(得分:2)
我不知道有关realloc
的实施问题,但此代码肯定有内存泄漏的机会:来自realloc
联机帮助页:
如果
realloc()
失败,则原始块保持不变;它没有被释放或移动。
并且,因为realloc
在失败时返回NULL
,如果失败,则会丢失指向已分配的内存块的唯一指针,因此存在内存泄漏。
为避免此问题,您应该:
char * temp=realloc(*str, len+2);
if(temp==NULL)
{
/* handle the error in some way */
}
else
*str=temp;
答案 3 :(得分:1)
尝试使用单独的变量重新分配,然后调用strcpy将str变量放入该空间,如下所示:
void AddChToString(char **str,char ch){
char *blah;
int len=(*str)?strlen(*str):0;
blah=realloc(NULL, len+2);
strcpy(blah, str);
(*str)[len]=ch;
(*str)[len+1]='\0'; }