问题描述
|
我有一段C ++代码可以从命名管道读取文本。相关部分是:
char s[256];
int num,fd;
string command;
command.erase(); //Clear the command string
cout << \"Command0:\" << endl << command << endl;
fd = open(FIFO_NAME,O_RDONLY); //Will block until a writer connects
do {
if ((num = read(fd,s,255)) == -1)
perror(\"read\");
else {
cout << \"Command1:\" << endl << command << endl;
s[num+1] = \'\\0\';
cout << \"Command2:\" << endl << command << endl;
//printf(\"read %d bytes: \\\"%s\\\"\\n\",num,s);
command += s;
}
} while (num > 0);
cout << \"Command:\" << endl << command << endl;
\“ commandX \” printfs是一些调试代码,稍后我将参考它们的输出。读入s的文本块可以很好地打印,但是在以空字符结束char数组之后,我最终在\“ command \”字符串中出现了二进制垃圾:
Command0:
Command1:
Command2:
除此之外,一切似乎都可以正常工作。 char []可正确连接到命令字符串,因此我得到了完整的字符串,只是前端有一些额外的二进制文件。我在这里有一个奇怪的数组越界问题正在写入命令的内存吗?
解决方法
在以下情况下,
if ((num = read(fd,s,255))
如果num = 255;
s[num+1] = \'\\0\';
将设置的s[256] = 0;
超出了s[0] to s[255]
的范围。
, 代替:
command += s;
你有没有尝试过:
command.append(s,num);
?
这样,您就不必担心以null终止等问题,只需添加读取的字符即可。