[英]Binary Data injected in String
我有一個 C++ 代碼塊,它從名為 pipe 讀取文本。 相關部分是:
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 是一些調試代碼,我將在一秒鍾內引用 output。 讀入 s 的文本塊打印得很好,但是在它以空值終止 char 數組之后,我最終在“命令”字符串中得到二進制垃圾:
Command0:
Command1:
Command2:
除此之外,一切似乎都運行良好。 char[] 正確連接到命令字符串,所以我最終得到了完整的字符串,只是前端有一些額外的二進制文件。 我是否有一個奇怪的數組越界問題正在寫入命令的 memory?
在以下情況下,
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);
?
這樣你就不需要為空終止等而煩惱,只需添加讀取的字符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.