码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-07-31 10:32:59      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:valgrind   uninitialised bytess   writebuf   

           最近使用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





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

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

标签:valgrind   uninitialised bytess   writebuf   

原文地址:http://blog.csdn.net/zhang2010kang/article/details/47165801

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!