Strcpy valgrind invalid read size

Possible duplicate:
Valgrind error when printing selected lines

I have code that just copies a string. I remember to allocate memory, but valgrind shows some errors, and I do not 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 did not understand why the error does not occur before the first printf ();

+4
source share

Source: https://habr.com/ru/post/1382863/


All Articles