while(!feof(fp1))分段错误

时间:2018-12-08 04:27:12

标签: c while-loop segmentation-fault feof

到目前为止,我还查看了其他答复,但没有答案。我已经使用cLion进行调试,以知道我的while(!feof(fp1))行是分段错误的原因。它链接到正确的主文件。这是用C语言编写的。

struct node //Create structure{
int value;
struct node *next;};
struct node *linked_list(void){

struct node *first = NULL;
struct node *prev = NULL;
struct node *cur = first;
struct node *new_node = malloc(sizeof(struct node));

if (new_node = NULL)
{
    printf("Memory not allocated properly!");
    exit(EXIT_FAILURE);
}


while (!feof(fp1))  //Loop until we reach EOF
{
    fscanf(fp1, "%d", &new_node->value);    //Get number from input file (fscanf)
    new_node->next = first;                 //Add number to linked list
    first = new_node;
    new_node = malloc(sizeof(struct node));
    if (new_node = NULL)
    {
        printf("Memory not allocated properly!");
        exit(EXIT_FAILURE);
    }

    if (first == NULL)
    {
        first = new_node;
        new_node->next = NULL;
        continue;
    }

    cur = first;

    while (cur->next != NULL && cur->next->value < new_node->value) {
        cur = cur->next;
    }

    if (cur->value < new_node->value)
    {
        new_node->next = cur->next;
        cur->next;
        prev->next;
        prev->next = new_node;
        new_node->next = cur;
    }
    else if (cur->next == NULL)
    {
        prev->next = new_node;
        new_node->next = NULL;
    }
    else if (cur->value == new_node->value)
    {
        cur->next;
        prev->next;
        free(new_node);         //Free memory
    }
    fprintf(fp2, "%d /t log10(%d) /r/n", fp1);
}

}

感谢您的帮助!谢谢!

0 个答案:

没有答案