我的从文本文件中删除行的 c 程序适用于小文件,但对于大文件有 stacksmash 错误
我正在开发一个程序来过滤 craigslist 结果列表;我想找一间相对便宜的房间出租。完成的程序将删除价格超过 600 美元的行,并创建一个新文件,但现在我删除带有 $ 字符的每一行,并打印到终端。
该程序在其自己的源代码上运行时工作正常,但是当我在从 Firefox 保存的 craigslist 结果的 html 页面上运行它时,它会打印直到结束 html 括号并抛出堆栈粉碎检测到的警告和回溯。我正在从 K&R 学习 C,所以如果这段代码看起来过时,那就是原因。
# 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 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;
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我想问题只是 HTML 包含至少一行长度超过 MAXLINE 个字符。您不会在任何地方检查是否即将超出数组的大小;如果你这样做,你确实会破坏堆栈。您的
while
循环可以检查p
是否小于MAXLINE
,如果不小于则打印一条消息,然后停止。如果不对程序进行相当大的更改,您就无法做任何其他事情。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 whetherp
was less thanMAXLINE
, print a message if not, and stop. You couldn't do anything else without fairly significant changes to your program.