Question

I'm having a problem debugging a linked lists program. It just crashes after the first few lines I figured it was probably a scanf problem and double checked but I still can't get it to run. It crashes in the middle of a function that creates a new node. Here is the code of the function and the main.

std* CreateNode()
{       
    std *newnd;
    char nm[20];
    double g;
    printf("\nCreating node\n");
    printf("\nEnter the student's name:\n");
    scanf("%s", &nm);
    printf ("\nEnter the student's GPA:\n");
    scanf("%lf", &g);
    strcpy( (newnd->name), nm);
    newnd->GPA = g;
    newnd->next = NULL;
    return newnd;
}

int main()
{
    list_head = (std*) malloc( sizeof(std) );
    list_tail=(std*) malloc( sizeof(std) );
    list_tail=(std*) malloc( sizeof(std) );

    list_head=CreateNode();
    A=CreateNode();
    B=CreateNode();
    C=CreateNode();
    PrintList(list_head);
    InsertBeg(A);
    InsertEnd(B);
    InsertMiddle(C);
    PrintList(list_head);
    SearchStudent();
    DeleteMiddle();
    DeleteEnd();
    DeleteBeg();
    PrintList(list_head);
    return 0;
}

When I run the program it stops executing right after I enter the gpa.

Any help would be very welcome I've tried everything I can think of. Thanks! :)

Was it helpful?

Solution

You declare

std* newnd;

however you never allocate memory for it before you try to access it's members.

std* newnd = malloc( sizeof *newnd  );

OTHER TIPS

in you program,

std *newnd;

is a pointer where did you allocate memory to it? you used the variable without allocating memory to it in

 strcpy( (newnd->name), nm);
 newnd->GPA = g;  
 newnd->next = NULL;

this results in program to crash. so allocate memory before using a variable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top