[英]Why does my .exe file crash after execution
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. 输出得到显示,但是在打印详细信息之后, .exe
文件崩溃。
#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. 显示输出后, .exe
文件停止工作。 Could you help me? 你可以帮帮我吗?
You should malloc(sizeof(struct Emp))
, not sizeof(struct Emp*)
. 您应该malloc(sizeof(struct Emp))
,而不是sizeof(struct Emp*)
。 No asterisk, you're allocating space for a whole struct, not for a pointer to it. 没有星号,您是为整个结构而不是指向它的指针分配空间。
You should scanf("%30s", p->name)
. 您应该scanf("%30s", p->name)
。 No &
needed, p->name
is already a pointer. 不需要&
, p->name
已经是一个指针。 Also, that 30
is very important , you have to limit the size of the scanned string to the available size, otherwise reading more than 30 characters would cause a buffer overflow (actually 29 if you count the \\0
added by %s
). 此外, 30
非常重要 ,您必须将扫描字符串的大小限制为可用大小,否则读取超过30个字符将导致缓冲区溢出(如果算上%s
添加的\\0
则实际上为29)。
Same goes for both p->gender
( %10s
, no &
) and p->mobno
( %12s
, no &
). p->gender
( %10s
,否&
)和p->mobno
( %12s
,否&
)都一样。
malloc应该具有sizeof(struct Emp)
而不是sizeof(struct Emp*)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.