[英]c - Valgrind - “Invalid write of size 1”
I'm completely lost on this, despite now trying to look for a solution for about two hours: 尽管现在试图寻找大约两个小时的解决方案,但我对此完全迷失了:
Valgrind is spitting out a bunch of invalid read of size 1 and invalid write of size 1 with this code, and I can't figure out how to fix it. Valgrind使用此代码吐出了一堆大小为1的无效读取和大小为1的无效写入,而我不知道该如何解决。
char *movieGetDirector(const movie *m)
{
char *tmp = NULL ;
tmp = malloc(strlen(m->director)+1) ;
strcpy(tmp, m->director) ;
return tmp ;
}
It's getting an invalid read of size 1 on the line with strlen and then an invalid write on the strcpy line. 在带有strlen的行上读取大小为1的无效读取,然后在strcpy线上得到无效写入。 I know that m->director is definitely a string, since testing it with gdb does reveal that it is a string and it has text.
我知道m-> director绝对是字符串,因为用gdb测试它确实显示出它是一个字符串并且包含文本。 All of the solutions on google for this error relate to not having that +1 there, but I have it there and it's still an issue.
google上针对此错误的所有解决方案都与那里没有+1有关,但是我在那里有,这仍然是一个问题。 How can I fix this?
我怎样才能解决这个问题?
your malloc/strlen/strcpy calls look fine. 您的malloc / strlen / strcpy调用看起来不错。 most likely the code that is setting up
m
and m's director
field are doing it wrong and the memory is corrupted. 设置
m
和m的director
字段的代码很可能做错了,并且内存已损坏。 you should double check where that variable is allocated & initialized. 您应该仔细检查该变量的分配和初始化位置。
that said, your function seems to be duplicating the existing strdup
function. 也就是说,您的函数似乎是在复制现有的
strdup
函数。 so you probably want to write: 所以你可能想写:
char *movieGetDirector(const movie *m)
{
return strdup(m->director);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.