简体   繁体   中英

pointer segmentation fault at 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)

any ideas?

First you allocate memory for init

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

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

init = initialize();

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

actual = init; 

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

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

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

Your initialize() function is returning null and you are creating a memory leak. Instead of returning null initialize the data members to reasonable values.

"Thank you! I saw that you should initialize your structure as null on a tutorial, I guess I did it on the wrong order.. Noobs right? haha I'm sorry about the dumb question, you guys are the best"

you are correct, you should initialize to null. But the code you have doesnt do that.

You need to do this

student *initialize(student * st)
{
   st->id = 0;
   st->grade = 0;
   st->next = NULL;
   return st;
}

or use calloc instead of malloc to make a student object (calloc clears the memry to 0)

or do

init = malloc ...
memset(init, 0, sizeof(student));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM