#include <stdio.h>
int main()
{
FILE* cmd = popen("grep Hello", "w");
fwrite("Hello\n", 6, 6, cmd);
fwrite("Hillo\n", 6, 6, cmd);
fwrite("Hello\n", 6, 6, cmd);
pclose(cmd);
}
The program above outputs:
Binary file (standard input) matches
Why does grep give the message, and how to fix it?
You are attempting to write 36 bytes instead of 6, effectively accessing bytes beyond the end of the string. Definitely undefined behaviour. Only the first
'\0'
byte is expected.Use
Or more simply: