Valgrind 抱怨函数 returns char 数组指针

Valgrind complains when function returns char array pointer

我想这是一个新手 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)

有人可以告诉我我做错了什么吗?提前致谢!

您正在 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;
}

还有do not cast malloc() results.

您正在 malloc() 两次但没有释放它们。因此,valgrind 抱怨泄漏。 释放你分配的内存块,应该没问题。

   char *p = copy(orig);
    printf("Copy reads     : %s\n", p);
    free(orig);
    free(p);