【问题标题】:C - segmentation fault when loop condition is ptr != NULL [closed]C - 循环条件为 ptr 时的分段错误!= NULL [关闭]
【发布时间】:2018-09-02 14:01:40
【问题描述】:

在 shareRecord while 循环中使用 ptr != NULL 时出现分段错误,但当我使用 ptr->next != NULL 时它似乎可以工作。

因此,当我使用 ptr->next != NULL 并取消注释 shareRecord 中的行时,代码可以正常工作。但是为什么它不能仅使用 ptr != NULL 工作。

请让我知道问题所在。

struct data *shareRecord(struct data *head, struct data *fileline){
    struct data *ptr;
    ptr = head;
    int flag = 0;
    while(ptr != NULL){
        if((strcmp(ptr->symbol, fileline->symbol) == 0) && (strcmp(ptr->type, fileline->type) == 0 )&& (ptr->time == fileline->time)){
            flag = 1;
            break;
        }
        ptr = ptr->next;
    }
    //if((strcmp(ptr->symbol, fileline->symbol) == 0) && (strcmp(ptr->type, fileline->type) == 0 )&& (ptr->time == fileline->time)){
            //flag = 1;
    //}
    if(ptr->next == NULL && flag == 0){
        return NULL;
    }   
    else
        return ptr;     
}
struct data *create_data(struct data *head, struct data *fileline){
    struct data *newdata, *ptr1, *ptr2;
    struct price *newprice, *priceptr1;
    newprice = (struct price *)malloc(sizeof(struct price *));
    newprice->amt = fileline->price->amt;
    newprice->next = NULL;
    if(head == NULL){

        newdata = (struct data *)malloc(sizeof(struct data));
        newdata->time = fileline->time;
        strcpy(newdata->symbol, fileline->symbol);
        strcpy(newdata->type, fileline->type);
        newdata->price = newprice;
        newdata->next = NULL;
        head = newdata;
    }
    else{
        ptr1 = head;
        ptr2 = head;
        if((ptr1 = shareRecord(head, fileline)) != NULL){
            priceptr1 = ptr1->price;
            while(priceptr1->next != NULL){
                priceptr1 = priceptr1->next;
            }
            priceptr1->next = newprice;
        }
        else{       
            while(ptr2->next != NULL){
                ptr2 = ptr2->next;
            }
            newdata = (struct data *)malloc(sizeof(struct data));
            newdata->time = fileline->time;
            strcpy(newdata->symbol, fileline->symbol);
            strcpy(newdata->type, fileline->type);
            newdata->price = newprice;
            newdata->next = NULL;
            ptr2->next = newdata;
        }
    }
    return head;
}

【问题讨论】:

标签: c pointers segmentation-fault


【解决方案1】:

ptr != NULL 导致错误时,循环将中断。这意味着当它中断时,ptr IS NULL 。所以下一行,

if(ptr->next == NULL && flag == 0){

您正在尝试使用 NULL 的属性,这应该导致错误。

【讨论】:

    猜你喜欢
    • 2023-03-07
    • 1970-01-01
    • 2021-12-20
    • 2020-05-18
    • 2023-04-08
    • 2013-08-21
    • 1970-01-01
    • 2016-07-18
    • 1970-01-01
    相关资源
    最近更新 更多