valgrind错误:Syscall param write(buf) points to uninitialis

valgrind错误:Syscall param write(buf) points to uninitialised bytes(s)

分类:Clinux

最近使用valgrind检查代码时,发现了一个比较鬼诡的bug:Syscall param write(buf) points to uninitialised bytes(s) 。在百度上找了很长时间的解决方法,但没有找到。最后用google搞清楚了原因,并解决了这个问题。

这是我主要参考的英文网站:

由于对齐等原因,我们定义变量等时应该先用memset对其进行初始化。然后再进行write、fwrite等调用。下面是一个具体的例子和其解决方法。

#include <stdio.h>#include <string.h>struct mystruct {char name[8];};int main(){struct mystruct s;FILE *f;strcpy(s.name, "12345");f = fopen("test.dat", "wb");fwrite(&s, 1, sizeof(s), f);fclose(f);return 0;} 上述代码用valgrind运行时会报Syscall param write(buf) points to uninitialised bytes(s) 错误。原因是我们调用fwrite时是向其写入8个字节,而只有前6个字节被明确赋值了。

解决方法1:加入memset进行清0.#include <stdio.h>#include <string.h>struct mystruct {char name[8];};int main(){struct mystruct s;memset(&s, 0, sizeof(s));FILE *f;strcpy(s.name, "12345");f = fopen("test.dat", "wb");fwrite(&s, 1, sizeof(s), f);fclose(f);return 0;}

解决方法2:用strlen(s.name + 1),刚好写入这么多字节数,代码如下:

#include <stdio.h>#include <string.h>struct mystruct {char name[8];};int main(){struct mystruct s;memset(&s, 0, sizeof(s));FILE *f;strcpy(s.name, "12345");f = fopen("test.dat", "wb");fwrite(&s, 1, sizeof(s.name) + 1, f);fclose(f);return 0;} 这样问题就解决啦。。。 原创文章,转载请注明:

版权声明:本文为博主原创文章,,未经博主允许不得转载。

上一篇Hadoop实战 Hadoop Pipes运行C++程序问题解决

顶0踩0

没有伞的孩子必须努力奔跑!

valgrind错误:Syscall param write(buf) points to uninitialis

相关文章:

你感兴趣的文章:

标签云: