[英]Stack Smashing Issue With Pipes, greps, wc in C
編輯:**問題已被答復:請參閱PaulMckenzie和Rishikesh Raje的評論
該功能的目的是使用管道使用參數pattern
在參數file
上調用grep,但是我的程序中的堆棧粉碎問題出現了。 它貫穿並一直運行到函數的末尾,但隨后抱怨堆棧崩潰。 這是我的代碼:
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 */
}
通過主帶參數運行它FILE =“somefile”圖案=“somepattern”輸出正確量somepatterns
在somefile
以及在最后的典型遷移錯誤檢查打印語句,此后它被終止堆棧溢出。
讀完堆棧粉碎后,似乎管道的某端過度擴展了對非法空間的讀取或寫入。 但我不確定這發生在哪里或為什么發生,因為直到功能結束,一切似乎都可以正常工作。 此處有關堆棧粉碎的其他文章暗示,是編譯器在代碼中拋出了金絲雀,表示可能發生堆棧粉碎時發生故障。 問題也不是main
。 誰能說明情況?
參考: http : //crasseux.com/books/ctutorial/Programming-with-pipes.html
該代碼主要基於此。
問題不在於管道。 問題與將字符串連接到空字符串變量grep_str有關,該變量顯然無法容納更多的字符串。 在評論中感謝Paul和Rishikesh
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.