我想这是一个新手C问题,但我找不到答案。这是我的代码:
#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-check = 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)
有人可以告诉我,我做错了什么?提前谢谢!
答案 0 :(得分:3)
你是malloc()两次但是没有释放()它们。因此,valgrind抱怨泄漏。 释放你分配的内存块,它应该没问题。
char *p = copy(orig);
printf("Copy reads : %s\n", p);
free(orig);
free(p);
答案 1 :(得分:2)
您正在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;
}