打印分配的字符串时,valgrind报告错误

时间:2011-11-03 15:19:22

标签: c printf valgrind

代码在这里:

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

int main()
{
    char* buf = malloc(3);
    strcpy(buf, "hi");
    printf("%s\n", buf);
    free(buf);
}

它编译为:

gcc a.c && valgrind ./a.out

错误信息在这里:

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

如果我使用以下内容(只有一个空格),valgrind不再报告错误也是非常奇怪的:

printf("%s \n", buf);

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:3)

这是一个错误,但在所有计算机上都无法重现。

在某些机器上,gcc使用例如printf()优化简单puts(),这可能涉及无效读取(或者只是valgrind认为如此)。

如果真的很重要,你可以“复杂化”printf格式。 %s\n之间的空格可以。

以下是类似的错误:C strings, strlen and Valgrind

这个答案结合了讨论中的评论。谢谢大家!

答案 1 :(得分:0)

我在自己的机器上运行它,我没有错误:

==61755== Memcheck, a memory error detector
==61755== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al.
==61755== Using Valgrind-3.5.0 and LibVEX; rerun with -h for copyright info
==61755== Command: ./a.out
==61755==
hi
==61755==
==61755== HEAP SUMMARY:
==61755==     in use at exit: 0 bytes in 0 blocks
==61755==   total heap usage: 1 allocs, 1 frees, 3 bytes allocated
==61755==
==61755== All heap blocks were freed -- no leaks are possible
==61755==
==61755== For counts of detected and suppressed errors, rerun with: -v
==61755== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 6)