开发者

My c program to remove lines from a text file works on a small file, but has a stacksmash error with a large file

I am working on a program to filter a list of craigslist results; I want to find a relatively cheap room for rent. The finished program will remove lines that have a price over $600, and create a new file, but for now I am removing every line with a $ character, and printing to the terminal.

The program works fine when run on its own source, but when I run it on an html page of craigslist results saved from Firefox, it prints until the closing html bracket and throws a stack smashing detected warning and a backtrace. I am learning C from K&R so if this code look开发者_C百科s antiquated that's why.

# include <stdio.h>
# define MAXLINE 300

main()
{
    char line[MAXLINE];
    int c;//current character
    int p = 0;//position in the line
    int flag = 0;//there is a dollar sign

    while ((c = getchar()) != EOF){
        line[p++] = c;
        if (c == '$'){
            flag = 1;
        }
        if (c == '\n'){
            if(flag == 0){//there was no $, print the line
                int i;
                for(i=0;i<p;i++){
                    putchar(line[i]);
                    line[i] = '\0';
                }
            }
            p = 0;
            flag = 0;
        }
    }
}


I imagine the problem is just that the HTML contains at least one line that is more than MAXLINE characters long. You don't check anywhere whether you're about to exceed the size of the array; if you do, you would indeed smash the stack. Your while loop could check whether p was less than MAXLINE, print a message if not, and stop. You couldn't do anything else without fairly significant changes to your program.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜