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

Answers


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];

  • 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).

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

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

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


Need Your Help

Strange but practical 2D bin packing optimization

algorithm math optimization knapsack-problem

I am trying to write an application that generates drawing for compartmentalized Panel. I have N cubicles (2D rectangles) (N &lt;= 40). For each cubicle there is a minimum height (minHeight[i]) ...

localtime_r support on MinGW

c++ windows mingw

I'm working on a Win32 multithread C++ project and I would like to use one of the localtime_* thread-safe alternatives to localtime().