【问题标题】:C - Why does returning an int result in a segmentation fault? [duplicate]C - 为什么返回 int 会导致分段错误? [复制]
【发布时间】: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(…);。 |看起来你根本没有理由 mallocfree 它实际上,或者甚至在循环之外声明它,除非你以某种方式卡在 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


【解决方案1】:

free() 要求您传递malloc()(或朋友)返回的相同指针。但是在这里,

imgpoint = strstr(line,"data-cfsrc");

您正在重新分配它。因此在调用free()未定义的行为

来自free()

free()函数释放ptr指向的内存空间, 必须由先前调用 malloc()、calloc() 或 重新分配()。否则,或者如果 free(ptr) 已经被调用 之前,会发生未定义的行为。如果 ptr 为 NULL,则不进行任何操作 执行。

(强调)。

【讨论】:

    猜你喜欢
    • 2021-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-24
    • 2016-10-31
    • 1970-01-01
    • 2021-07-18
    • 2020-04-15
    相关资源
    最近更新 更多