我有一段 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 的文本 block 打印得很好,但在它以 null 终止 char 数组之后,我最终在“命令”字符串中得到了二进制垃圾:
Command0:
Command1:
Command2:
除此之外,一切似乎都正常。 char[] 正确地连接到命令字符串上,所以我最终得到了完整的字符串,只是前端有一些额外的二进制文件。我这里是否有一个奇怪的数组越界问题正在写入命令的内存?
最佳答案
在下面的情况下,
if ((num = read(fd, s, 255))
如果 num = 255;
那么
s[num+1] = '\0';
将设置 s[256] = 0;
,这超出了 s[0] 到 s[255]
的范围。
关于c++ - 二进制数据注入(inject)字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6339018/