c - scanf 指针段错误

标签 c pointers memory segmentation-fault

<分区>

一点帮助? 我很确定答案一定很愚蠢,但我不明白为什么我在 scanf 之后立即遇到段错误。我已经盯着我的代码看了很长时间了:

#include<stdio.h> 
#include<stdlib.h> 
#include<string.h> 

typedef struct Student{ 

    int grade, id; 
    struct Student *next; 
}student; 


student *initialize(){
    return NULL;
}

int main(){ 
    student *init; 
    student *nxt; 
    student *actual;
    int resp;

    init = (student*)malloc(sizeof(student)); 
    init = initialize();

    actual = init; 

    while(1){ 
        printf("type grade:\n"); 
        scanf("%d", &actual->grade); 
        printf("type id:\n"); 
        scanf("%d", &actual->id); 
        printf("wanna continue? (1-YES e <other>-NO)\n"); 
        if(resp==1){ 
            actual->next=(student*)malloc(sizeof(student)); 
            nxt=actual->next; 
        }else 
            break; 
    }

    actual->next=NULL;
    return 0; 
}

没什么大不了的,对吧?有一个结构,我想将一个值扫描到其中。在我的终端上,我得到:

type grade:
3
Segmentation fault (core dumped)

有什么想法吗?

最佳答案

首先你为init分配内存

init = (student*)malloc(sizeof(student)); 

但是您立即将 init 设置为 NULL,并在此处使用您的 initialize() 函数的返回值

init = initialize();

这不仅是内存泄漏,而且您接下来在这里将 actual 设置为 NULL

actual = init; 

然后在你的 while 循环中,你在几个地方取消引用 actual(它是 NULL)

scanf("%d", &actual->grade); 

取消引用 NULL 指针是未定义的行为,这可能是您的错误来源。

关于c - scanf 指针段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33661383/

相关文章:

c - 使用 。检索结构中的值

c - 包含包含指向自身的结构指针的 union 的结构使用 '.' 访问而不是 '->' ,混淆

python - scipy.sparse.csr_matrix.toarray() 的大量内存使用

使用 %s 时无法访问数组的第一个下标,但可以使用 %c

c - 从文件读取时如何处理数据或字符-1,因为EOF也是-1

c - 制作库: conflicting types in header and source file

将指针数组值复制到 C 中另一个数组的末尾

无法将字符串分配给结构内的指针

python - Python子串提取的效率如何?

java - Java 多态中对象的字段访问和内存分配