C语言 Valgrind:大小 1 的读取无效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14067403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Valgrind: Invalid read of size 1
提问by user1934103
I'm having an issue with valgrind: This is my program (well the main part where the errors appear):
我在使用 valgrind 时遇到问题:这是我的程序(以及出现错误的主要部分):
int main()
{
char comanda[N];
....
char *p;
while( fgets(comanda,100,stdin)!=NULL)
{
p=strtok(comanda," \n");
if (strcmp(comanda,"INIT")==0)
{
p=strtok(NULL," ");
Init(n);
}
395 >>if (strcmp(p,"DUMP")==0)
{
Dump(n);}
if (strcmp(p,"ALLOC")==0)
{
Alloc(j,n);
}
....return 0;}
And when i run valgrind it says:
当我运行 valgrind 时,它说:
Invalid read of size 1 at 0x401569: main (:395) Address 0x0 is not stack'd malloc'd or (recently) free'd
Invalid read of size 1 at 0x401569: main (:395) Address 0x0 is not stack'd malloc'd or (recently) free'd
I can't figure out what's the matter with this program.
我无法弄清楚这个程序有什么问题。
回答by Mats Petersson
How to read this:
如何阅读:
Invalid read of size 1
大小 1 的无效读取
Your program is trying to read one byte from somewhere that Valgrind doesn't like.
您的程序试图从 Valgrind 不喜欢的地方读取一个字节。
at 0x401569: main (:395)
在 0x401569:主要 (:395)
Where in the code this happens (clearly strcmp has been inlined)
在代码中发生这种情况(显然 strcmp 已被内联)
Address 0x0 is not stack'd malloc'd or (recently) free'd
地址 0x0 未被堆栈'd malloc'd 或(最近)释放'd
What the address it was reading - 0x0 is "NULL". The rest of the statement just says why it's invalid (it's not from the stack, it's not something you've got from malloc, and not been freed recently). The "recently" is mentioned because valgrind keeps track of freed memory for a limited number of frees, so it can't say for sure that it wasn't freed a million frees back - in this case it wasn't, but if you see a message like that, it MAY be that it has become invalid because it was freed ages ago. The address would not be zero tho' (or near zero).
它读取的地址 - 0x0 是“NULL”。语句的其余部分只是说明了为什么它无效(它不是来自堆栈,它不是您从 malloc 获得的,并且最近没有被释放)。提到“最近”是因为 valgrind 会跟踪有限数量的释放的已释放内存,因此不能肯定地说它没有释放一百万次释放 - 在这种情况下它不是,但如果你看到这样的消息,可能是因为它很久以前就被释放了,所以它已经失效了。地址不会为零(或接近零)。
回答by codaddict
It is possible for strtokto return NULL when there are no more tokens left.
strtok当没有更多标记时,可以返回 NULL。
When you pass NULL to strcmpit is an undefined behavior as you de-reference NULL there.
当您将 NULL 传递给strcmp它时,这是一种未定义的行为,因为您在那里取消引用 NULL。

