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

来源:互联网 发布:java扑克牌发牌程序 编辑:程序博客网 时间:2024/06/05 08:43

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

        这是我主要参考的英文网站:http://comments.gmane.org/gmane.comp.debugging.valgrind/7856

        由于对齐等原因,我们定义变量等时应该先用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;}
          这样问题就解决啦。。。
          原创文章,转载请注明:http://blog.csdn.net/zhang2010kang





0 0
原创粉丝点击