0

I guess this is a newbie C question but I just could not find the answer. This is my code:

#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));
}

It works fine, however valgrind --leak-check=yes complains:

==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)

Could someone please tell me what am I doing wrong? Thanks in advance!

2 Answers2

3

You are malloc()'ing twice but do not free() them. Hence, valgrind complains about leaks. Free the memory blocks you allocate and it should be fine.

   char *p = copy(orig);
    printf("Copy reads     : %s\n", p);
    free(orig);
    free(p);
P.P
  • 117,907
  • 20
  • 175
  • 238
2

You are allocating memory block in the copy function, but never free it. So your code produces a memory leak, which is reported by the Valgrind. Correct version of your code should be

#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;
}

Also do not cast malloc() results.

Community
  • 1
  • 1
Ari0nhh
  • 5,720
  • 3
  • 28
  • 33