2011-06-14 38 views
0

我有一块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打印就好了,但空终止字符数组后,我在“命令”的字符串结束与二进制垃圾:

Command0: 

Command1: 

Command2: 

除此之外,一切都显得工作正常。 char []正确连接到命令字符串上,所以我最终得到了完整的字符串,只是在前端添加了一些额外的二进制文件。我是否有一个奇怪的数组越界问题,这是写入命令的内存?

+2

我认为空终止应该在索引'num'而不是'num + 1'处。如果你已经读过'num'字符,那么它们从'0'填充到'num-1'索引。 – Mahesh 2011-06-14 04:28:12

+1

它应该是s [num] ='\ 0'而不是num + 1。 – Duck 2011-06-14 04:28:21

回答

3

在下面的条件下,

if ((num = read(fd, s, 255)) 

如果num = 255;然后

s[num+1] = '\0'; 

将设置s[256] = 0;其超出范围为s[0] to s[255]

+0

男人,这是一个愚蠢的。我记得读一个人物离开房间,然后去反正跑完了。谢谢。 – RedPeasant 2011-06-14 05:17:50

1

相反的:

command += s; 

你试过:

command.append(s, num); 

这种方式你不需要打扰null终止等,只是添加阅读字符。