0

While I was inputting "stuList[1].name", an error occurred and the program crashed. How do I fix this?

#include <stdio.h>
#include <conio.h>

typedef struct student
    {
        int id;
        char *name;
        float percentage;
    } student;

int main()
{
    student stuList[3];
    stuList[0].name = "vermidonhapic"; 
    stuList[2].name = "didiervermiyer";

    scanf("%s\n",&stuList[1].name);

    printf(" name is: %s \n", stuList[0].name);
    printf(" name is: %s \n", stuList[2].name);  
    printf(" name is: %s \n", stuList[1].name);

    system("PAUSE");
}
1
  • 2
    scanf() with a "%s" format is extremely dangerous, even if the pointer points to properly allocated memory. It will read an arbitrarily long string into the destination buffer; there's no way to prevent it from writing past the end of your array. Commented Jan 19, 2012 at 21:30

4 Answers 4

2

In this command: scanf("%s\n",&stuList[1].name);

You are scanning string from input without actually allocating the required memory.

This results in trying to write the data in an unkown address, which is not yours, which results in a segmentation fault.

To fix it, first allocate memory: stuList[1].name = malloc(MAX_LENGTH);, and only after: scan the string from stdin.

Sign up to request clarification or add additional context in comments.

Comments

2

name is just a pointer that isn't pointing to memory you own, so writing through it will corrupt memory. You need to allocate some memory on it with malloc(), or make it an array rather than a pointer.

Comments

2

stuList[1].name is an invalid pointer as it has not been initialized to point to a valid object.

You should dynamically allocate memory (through malloc function) for stuList[1].name so scanf could write to an allocated object.

stuList[1].name = malloc(size_enough_to_store_your_string);

Moreover, stuList[1].name is a pointer to char so you should use stuList[1].name and not &stuList[1].name (pointer to a pointer to char) in your scanf function call.

1 Comment

@amit thanks, I misread the string literal pointers assignments. Fixed.
1

You forgot to allocate memory for stuList[1].name. You need to allocate it from the heap with malloc or stack allocate it.

stuList[1].name = malloc(MAX_NAME_LENGTH);//heap allocation
//use stuList[1].name
free(stuList[1].name);

char buffer[MAX_NAME_LENGTH];//stack allocation
stuList[1].name = buffer;

I've omitted all error checking, protection against over-running buffers etc.

Since stuList[1].name is a pointer, you are incorrect in taking its address in your scanf.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.