EDIT: ** QUESTION HAS BEEN ANSWERED: see comments by PaulMckenzie and Rishikesh Raje
The intention of this function is to call grep on parameter file
with parameter pattern
using pipes, but I am having an issue with stack smashing in my program. It runs through and works straight through to the end of the function, but then complains of stack smashing.
Here's my code:
void count_pattern(char *file, char *pattern) {
int bytes_read;
int nbytes = 20000;
char *read_string;
char grep_str[] = "";
FILE *grep_pipe;
FILE *wc_pipe;
strcat(grep_str, "grep ");
strcat(grep_str, pattern);
strcat(grep_str, " ");
strcat(grep_str, file);
strcat(grep_str, "\0");
grep_pipe = popen (grep_str, "r");
wc_pipe = popen ("wc -l", "w");
/* Pipe Error Checking*/
if ((!grep_pipe) || (!wc_pipe))
{
fprintf (stderr,"One or both pipes failed.\n");
}
/* Read from grep_pipe until EOF? */
read_string = (char *) malloc (nbytes + 1);
bytes_read = getdelim (&read_string, &nbytes, -1, grep_pipe);
/* Close grep_pipe */
if (pclose (grep_pipe) != 0)
{
fprintf (stderr, "Could not run 'grep'.\n");
}
/* Send output of 'grep' to 'wc' */
fprintf (wc_pipe, "%s", read_string);
/* Close wc_pipe */
if (pclose (wc_pipe) != 0)
{
fprintf (stderr, "Could not run 'wc'.\n");
}
printf("%s\n\n",grep_str); /* migrating bug-check print statement */
}
Running it through the main with parameters file="somefile" pattern="somepattern" outputs the correct amount of somepatterns
in the somefile
as well as the typical migrating bug-checking print statement at the very end, after which it gets terminated for stack smashing.
Having read up on stack smashing, it seems like some end of the pipe is overextending a read or write into illegal space. I'm not sure where or why that's happening, however, since everything seems to work fine until function end. Other posts on here about stack smashing imply that it is the compiler throwing a canary into the code that signals failure when stack smash may happen. The problem is not with the main
either. Can anyone shed any light on the situation?
Reference: http://crasseux.com/books/ctutorial/Programming-with-pipes.html
Is where this code is mostly based off of.
The issue was not with the pipes. The issue had to do with the concatenation of strings to the empty string variable grep_str that clearly could not fit more strings in it. Credit to Paul and Rishikesh in the comments