I've got a block of C++ code that reads text from a named pipe. The relevant section is:
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;
The "commandX" printfs are some debug code that I'll reference the output of in a second. The chunks of text that get read into s print just fine, but after it null-terminates the char array, I end up with binary junk in the "command" string:
Command0:
Command1:
Command2:
Other than that, everything appears to work fine. The char[] concatenates onto the command string correctly, 开发者_开发技巧so I end up with the complete string, just with some extra binary on the front end. Am I having a weird array out of bounds problem here that is writing to command's memory?
In the below condition,
if ((num = read(fd, s, 255))
If num = 255;
then
s[num+1] = '\0';
will set s[256] = 0;
which is out of range for s[0] to s[255]
.
Instead of:
command += s;
Have you tried:
command.append(s, num);
?
This way you don't need to bother with null-terminating etc, just add the read characters.
精彩评论