Valgrind的抱怨,当函数返回字符数组的指针
问题描述:
我想这是一个新手ç的问题,但我无法找到答案。这是我的代码:Valgrind的抱怨,当函数返回字符数组的指针
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *copy(char *in) {
char *out = (char *) malloc(strlen(in)+1);
strcpy(out,in);
return out;
}
int main() {
char *orig = (char *) malloc(100);
strcpy(orig,"TEST");
printf("Original reads : %s\n",orig);
printf("Copy reads : %s\n",copy(orig));
}
它工作正常,但是的valgrind --leak检查= YES抱怨:
==4701== Memcheck, a memory error detector
==4701== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==4701== Using Valgrind-3.10.0 and LibVEX; rerun with -h for copyright info
==4701== Command: ./copy
==4701==
Original reads : TEST
Copy reads : TEST
==4701==
==4701== HEAP SUMMARY:
==4701== in use at exit: 105 bytes in 2 blocks
==4701== total heap usage: 2 allocs, 0 frees, 105 bytes allocated
==4701==
==4701== 5 bytes in 1 blocks are definitely lost in loss record 1 of 2
==4701== at 0x4C28C20: malloc (vg_replace_malloc.c:296)
==4701== by 0x400609: copy (in /root/alfred/copy)
==4701== by 0x40066C: main (in /root/alfred/copy)
==4701==
==4701== 100 bytes in 1 blocks are definitely lost in loss record 2 of 2
==4701== at 0x4C28C20: malloc (vg_replace_malloc.c:296)
==4701== by 0x400638: main (in /root/alfred/copy)
==4701==
==4701== LEAK SUMMARY:
==4701== definitely lost: 105 bytes in 2 blocks
==4701== indirectly lost: 0 bytes in 0 blocks
==4701== possibly lost: 0 bytes in 0 blocks
==4701== still reachable: 0 bytes in 0 blocks
==4701== suppressed: 0 bytes in 0 blocks
==4701==
==4701== For counts of detected and suppressed errors, rerun with: -v
==4701== ERROR SUMMARY: 2 errors from 2 contexts (suppressed: 0 from 0)
可能有人请告诉我,我究竟做错了什么?提前致谢!
答
您正在分配copy
函数中的内存块,但从不释放它。所以你的代码会产生一个内存泄漏,这是Valgrind报告的。你的代码的正确版本应该是
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *copy(char *in) {
char *out = malloc(strlen(in)+1);
//You need to check malloc result here!
strcpy(out,in);
return out;
}
int main() {
char *orig = (char *) malloc(100);
strcpy(orig,"TEST");
printf("Original reads : %s\n",orig);
char* copy = copy(orig);
printf("Copy reads : %s\n",copy);
free(orig);
free(copy);
return 0;
}
答
您是的malloc()'荷兰国际集团两次,但不免费()他们。因此,valgrind抱怨泄漏。 释放你分配的内存块,它应该没问题。
char *p = copy(orig);
printf("Copy reads : %s\n", p);
free(orig);
free(p);
+0
谢谢!这解决了它。 –
固定!还要感谢关于转换malloc()结果和注意缺失返回0的建议。 –