0

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 looks 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;
        }
    }
}
Corey
  • 257
  • 1
  • 4
  • 14

1 Answers1

4

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.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
  • THe program printed the entire file to terminal, ending with – Corey Sep 24 '11 at 01:34
  • No, overrunning the top of the stack isn't necessarily going to crash the program; the space above the top stack frame is just unused space. The values of c and p might be overwritten, but as long as they're small integers, you might just get one bad character or a few repeated ones, and then the program would continue to work OK. Why not add a `printf` statement to print the value of `p` at the end of each line, and comment out the `putchar()` so it'll be easy to see them? You may be surprised. – Ernest Friedman-Hill Sep 24 '11 at 02:07
  • you were right, every line was under 300 except one culprit that was over 1000 chars long – Corey Sep 24 '11 at 04:50