问题描述
在code是在这里:
#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
该错误信息是在这里:
The error message is here:
==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报告没有更多的错误:
It is also very strange that valgrind reports no more errors if I use the following (just one more space):
printf("%s \n", buf);
会有人帮帮我吗?
Would anyone please help me?
推荐答案
这是一个错误,但在所有机器上不可重现。
This is a bug, but not reproducible on all machines.
在一些机器,GCC优化简单的的printf()
用,例如,看跌期权()
,这可能可能涉及非法读取(或只是Valgrind的是这样认为的)。
On some machines, gcc optimizes simple printf()
with, for example, puts()
, which could possibly involve invalid read (or just valgrind thinks so).
如果它真的很重要,你可以'复杂'的的printf
格式。之间的空格%S
和 \\ n
会怎么做。
If it really matters, you can 'complicate' the printf
format. A space between %s
and \n
would do.
下面是一个类似的错误:
Here is a similar bug: C strings, strlen and Valgrind
这答案结合的讨论意见。谢谢大家!
This answer combines comments in the discussion. Thank you all!
这篇关于打印分配的字符串时,Valgrind的报告错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!