Note that there are some explanatory texts on larger screens.

plurals
  1. POstrcpy valgrind invalid read of size
    primarykey
    data
    text
    <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/7997379/the-valgrind-reports-error-when-printing-allocated-strings">The valgrind reports error when printing allocated strings</a> </p> </blockquote> <p>I have code which simply copies string. I remember to allocate memory, but valgrind shows some errors and I don't understand this.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; typedef struct foo { char *a; }; struct foo* create(char *lol){ struct foo *test = malloc(sizeof(struct foo)); test-&gt;a = malloc(sizeof(char) * (strlen(lol)+1)); strcpy(test-&gt;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-&gt;a); printf("%s\n", c-&gt;a); free(a); free(c-&gt;a); free(c); return 0; } </code></pre> <p>Gives valgrind output:</p> <pre><code>==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) </code></pre> <p>I didn't get why error is not occuring before first printf();</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload