Note that there are some explanatory texts on larger screens.

plurals
  1. POThe valgrind reports error when printing allocated strings
    primarykey
    data
    text
    <p>The code is here:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; int main() { char* buf = malloc(3); strcpy(buf, "hi"); printf("%s\n", buf); free(buf); } </code></pre> <p>It's compiled with:</p> <pre><code>gcc a.c &amp;&amp; valgrind ./a.out </code></pre> <p>The error message is here:</p> <pre><code>==1421== Memcheck, a memory error detector ==1421== Copyright (C) 2002-2010, and GNU GPL'd, by Julian Seward et al. ==1421== Using Valgrind-3.6.1 and LibVEX; rerun with -h for copyright info ==1421== Command: ./a.out ==1421== ==1421== Invalid read of size 8 ==1421== at 0x4EA96C1: ??? (in /lib/libc-2.14.1.so) ==1421== by 0x4E92D3B: puts (in /lib/libc-2.14.1.so) ==1421== by 0x4005BB: main (in /home/peter/a.out) ==1421== Address 0x51b4040 is 0 bytes inside a block of size 3 alloc'd ==1421== at 0x4C2740D: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) ==1421== by 0x400595: main (in /home/peter/a.out) ==1421== hi ==1421== ==1421== HEAP SUMMARY: ==1421== in use at exit: 0 bytes in 0 blocks ==1421== total heap usage: 1 allocs, 1 frees, 3 bytes allocated ==1421== ==1421== All heap blocks were freed -- no leaks are possible ==1421== ==1421== For counts of detected and suppressed errors, rerun with: -v ==1421== ERROR SUMMARY: 2 errors from 1 contexts (suppressed: 6 from 6) </code></pre> <p>It is also very strange that valgrind reports no more errors if I use the following (just one more space):</p> <pre><code>printf("%s \n", buf); </code></pre> <p>Would anyone please help me?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    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