scanf 处的指针分段错误 [英] pointer segmentation fault at scanf

查看:78
本文介绍了scanf 处的指针分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

a Little help? I'm pretty sure the answer must be something silly, but I cannot see why am I getting a segmentation fault right after my scanf. I've been staring at my piece of code for a long time now:

#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; 
}

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

No big deal, right? There is a struct, I want to scan a value into it. on my terminal, I get:

type grade:
3
Segmentation fault (core dumped)

有什么想法吗?

推荐答案

首先你为 init

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

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

but you immediately set init to NULL with the return value of your initialize() function here

init = initialize();

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

Not only is this a memory leak, but you next set actual to NULL here

actual = init; 

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

Then later in your while loop you dereference actual (which is NULL) in several places such as here

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

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

Dereferencing NULL pointers is undefined behaviour and this is a likely source of your error.

这篇关于scanf 处的指针分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆