【发布时间】:2016-10-19 09:17:21
【问题描述】:
我正在从事一个小型私人项目,该项目从 html 页面源中读取一些链接。我逐行读取 html 文件,然后检查该行是否包含“data-cfsrc”,它总是在我想要阅读的链接之前。这工作正常,直到我尝试释放指向关键字(“data-cfsrc”)开始位置的指针。
我已尝试在多个点上释放它,但它仅在我尚未对其进行任何操作时才有效。
这是我的代码:
FILE *fp_w, *fp_r;
fp_r = fopen("page.html","r");
fp_w = fopen("bg_list.txt","a");
char line[1024],img[512],c;
//char *imgpoint = malloc(sizeof(char)*512);
char *imgpoint;
int i,imgcount = 0;
while(imgcount<15){
// read line
i = 0;
do{
c = fgetc(fp_r);
line[i] = c;
i++;
}while(c!='\n');
line[i] = '\0';
if(strstr(line,"data-cfsrc") != NULL){
imgpoint = strstr(line,"data-cfsrc");
strcpy(img,imgpoint);
c = 0;
for(i=0; c!=34; i++){
img[i] = img[i+12];
c = img[i+13];
}
img[i] = '\0';
fprintf(fp_w,"%s\n",img);
imgcount++;
printf("imgcount = %d\n",imgcount);
}
}
fclose(fp_r);
fclose(fp_w);
//free(imgpoint);
return 0;
编辑:如前所述,我完全删除了 free(),但现在我的程序在调用 return 时仍然导致分段错误。
编辑 2:完全省略了 imppoint 指针。一切仍然有效,但返回时我仍然遇到分段错误。
【问题讨论】:
-
你正在修改
imgpointimgpoint = strstr(…);。 |看起来你根本没有理由malloc或free它实际上,或者甚至在循环之外声明它,除非你以某种方式卡在 C89 上。 -
做
imgpoint = strstr(line,"data-cfsrc");你分配给imgpoint堆栈内存 -
如果您在
malloc尚未返回的指针上调用free(这就是您在此处所做的),您会得到未定义的行为。 -
您的代码中似乎不需要变量“imgpoint”。您可以将
imgpoint = strstr(line,"data-cfsrc");strcpy(img,imgpoint);替换为strcpy(img,strstr(line,"data-cfsrc"));。
标签: c