4

Possible Duplicate:
The valgrind reports error when printing allocated strings

I have code which simply copies string. I remember to allocate memory, but valgrind shows some errors and I don't understand this.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct foo {
        char *a;
};

struct foo*
create(char *lol){
        struct foo *test = malloc(sizeof(struct foo));
        test->a = malloc(sizeof(char) * (strlen(lol)+1));
        strcpy(test->a, lol);
        return test;
}

int main()
{
        char *a = malloc(5*sizeof(char));
        strcpy(a, "test");
        struct foo *c = create("test");
        printf("%s\n%s\n", a, c->a);
        printf("%s\n", c->a);
        free(a);
        free(c->a);
        free(c);
        return 0;
}

Gives valgrind output:

==13825== Memcheck, a memory error detector
==13825== Copyright (C) 2002-2011, and GNU GPL'd, by Julian Seward et al.
==13825== Using Valgrind-3.7.0 and LibVEX; rerun with -h for copyright info
==13825== Command: ./a.out
==13825== 
test
test
==13825== Invalid read of size 4
==13825==    at 0x40C301B: ??? (in /lib/libc-2.14.1.so)
==13825==    by 0x4066242: (below main) (in /lib/libc-2.14.1.so)
==13825==  Address 0x41ca09c is 4 bytes inside a block of size 5 alloc'd
==13825==    at 0x402A018: malloc (in /usr/lib/valgrind/vgpreload_memcheck-x86-linux.so)
==13825==    by 0x80484F3: create (in /home/patseb/src/mgr/test/a.out)
==13825==    by 0x8048550: main (in /home/patseb/src/mgr/test/a.out)
==13825== 
test
==13825== 
==13825== HEAP SUMMARY:
==13825==     in use at exit: 0 bytes in 0 blocks
==13825==   total heap usage: 3 allocs, 3 frees, 14 bytes allocated
==13825== 
==13825== All heap blocks were freed -- no leaks are possible
==13825== 
==13825== For counts of detected and suppressed errors, rerun with: -v
==13825== ERROR SUMMARY: 1 errors from 1 contexts (suppressed: 13 from 8)

I didn't get why error is not occuring before first printf();

Community
  • 1
  • 1
patseb
  • 651
  • 1
  • 8
  • 20
  • 3
    Just a little advice: use `strdup` instead of `malloc`ing and `strcpy`ing the string. – Constantinius Nov 24 '11 at 10:31
  • 4
    It's a bug. See [this thread](http://stackoverflow.com/questions/7997379/the-valgrind-reports-error-when-printing-allocated-strings). Change `printf("%s\n", c->a);` to `printf("%s \n", c->a);` and you'll make it go away. – cnicutar Nov 24 '11 at 10:31
  • No need to use `* sizeof(char)`. From the K&R: "_When sizeof is applied to a char, the result is 1;_" – calandoa Nov 24 '11 at 12:32

0 Answers0