user261002
user261002

Reputation: 2252

segmentation fault in C

I am trying to write this code, but it gives me segmentation fault after running the program, could you please help to sort it out?

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

typedef struct{
    int salary;
    char* name;
} employee ;

int main(){
    employee p[2];
        int i;
        for(i=0;i<2; i++){
            printf("enter sal ");
            scanf("%d", &p[i].salary);

           printf("enter name ");
           scanf("%s", &p[i].name);
        }
        for(i=0;i<2; i++){
           printf("p %d",p[i].salary);
           printf("p %s",p[i].name);
        }
    return 0;
}

Upvotes: 0

Views: 420

Answers (7)

ChrisJ
ChrisJ

Reputation: 5241

You need to allocate memory for the "name" string in your structure. Do this using malloc() or by declaring name as an array of a given size (char name[SIZE]).

Upvotes: 0

Alam
Alam

Reputation: 1596

You are not allocating memory for char* name. change your data structure to

typedef struct
{ 
    int salary; 
     char name[50]; 
} 

or allocate memory using malloc

Upvotes: 1

codaddict
codaddict

Reputation: 454912

The structure field name is just a wild character pointer.

char* name;

you are reading the user input as:

scanf("%s", &p[i].name);

into the memory pointed by name which could be anywhere.

To fix this you need to dynamically allocate memory pointed to by name or you can change name to a char array of size one greater than the max length of the name possible.

char name[MAX];

Upvotes: 1

Diego Sevilla
Diego Sevilla

Reputation: 29001

You have to reserve memory for the name member of each instance of employee:

p[i].name = (char*)malloc(expected_max_size);

just before the scanf for that variable. Declaring a pointer to char char* does not assign memory for the actual string pointed to, but just for the pointer itself, and in your example it is not initialized. By using malloc you reserve a piece of memory and makes the pointer point to it. You have to be careful with bounds checking, because you have to reserve the memory beforehand, enough to hold what the user is writing.

Upvotes: 0

frast
frast

Reputation: 2740

You forgot to allocate memory for p[i].name.

Upvotes: 0

NPE
NPE

Reputation: 500157

  • You need to allocate memory for the name field: p[i].name = (char*)malloc(MAX_NAME_LEN)
  • Also, the scanf("%s", &p[i].name) should read scanf("%s", p[i].name).

Upvotes: 5

Andreas Wong
Andreas Wong

Reputation: 60506

You don't need the & operator when scanf'ing to pointer. And you need to malloc p[i].name

       scanf("%s", p[i].name);

Upvotes: 1

Related Questions