0

This is a program to store employee details and access them using pointer variables. The output is getting displayed but after printing the details the .exe file crashes.

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct Emp
{
    char name[30];
    int id;
    char gender[10],mobno[12];
};
int main()
{
   struct Emp *p;
   p=(struct Emp*)malloc(sizeof(struct Emp*));
   printf("\nEnter the employee name : ");
   scanf("%s",&p->name);
   printf("Enter the employee id : ");
   scanf("%d",&p->id);
   printf("Enter your gender : ");
   scanf("%s",&p->gender);
   printf("Enter employee number : ");
   scanf("%s",&p->mobno);

   printf("\nEmployee details:-\nEmployee id : %d\nEmployee name :: %s\nEmployee's Gender : %s\nEmployee's Mobile number : %s\n ",p->id,p->name,p->gender,p->mobno);
   free(p);
   return 0;
}

After displaying the output, the .exe file stops working. Could you help me?

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128

2 Answers2

3
  1. You should malloc(sizeof(struct Emp)), not sizeof(struct Emp*). No asterisk, you're allocating space for a whole struct, not for a pointer to it.

  2. You should scanf("%29s", p->name). No & needed, p->name is already a pointer. Also, that 29 is very important, you have to limit the size of the scanned string to the available size, otherwise reading more than 29 characters would cause a buffer overflow (considering the final \0 added by %s).

  3. Same goes for both p->gender (%9s, no &) and p->mobno (%11s, no &).

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
0

malloc should have sizeof(struct Emp) instead of sizeof(struct Emp*)

mdasari
  • 423
  • 4
  • 11