为什么这个C程序崩溃? [英] Why does this C program crash?
问题描述
我已经反复考虑这个了至少一个小时,我仍然无法找出问题所在。
的#include<&stdio.h中GT;typedef结构
{
INT水平;
字符*名称;
}基地;基地baseStruct;INT主(INT ARGC,CHAR *的argv [])
{
scanf函数(%S,baseStruct.Name);
scanf函数(%d个,&安培; baseStruct.Level);
的printf(%S ::%d级\\ n,baseStruct.Name,baseStruct.Level);
返回0;
}
会发生什么事,我去输入姓名字符串,然后当我输入,输入整数程序崩溃。这是怎么回事?
scanf函数(%S,...)
这需要一个缓冲( scanf函数
需要写的到的它),你给它一个未初始化的指针,可能指向任何地方。
考虑执行下列操作之一:
-
请
名称
字符缓冲区,而不是:typedef结构
{
INT水平;
CHAR名称[100];
}基地; -
从堆初始化:
baseStruct.Name =的malloc(100); / *不要忘记用`free()的清理`* /
您还应该指定 scanf函数
格式字符串prevent溢出最大字符串长度:
/ *假设'名'是一个很长的缓冲区100个字符* /
scanf函数(%99秒,baseStruct.Name);
I've mulled over this for at least an hour and I still can't find out what the problem is.
#include <stdio.h>
typedef struct
{
int Level;
char* Name;
} Base;
Base baseStruct;
int main(int argc, char *argv[])
{
scanf("%s", baseStruct.Name);
scanf("%d", &baseStruct.Level);
printf("%s :: Level %d\n", baseStruct.Name, baseStruct.Level);
return 0;
}
What happens is, I go and enter the "Name" string, then when I type and enter the integer the program crashes. What is going on?
scanf("%s", ...)
This expects a buffer (scanf
needs to write into it) and you give it an uninitialized pointer, that could point anywhere.
Consider doing one of the following:
Make
Name
a character buffer instead:typedef struct { int Level; char Name[100]; } Base;
Initialize it from the heap:
baseStruct.Name = malloc(100); /* do not forget to cleanup with `free()` */
You should also specify max string length in scanf
format string to prevent overflow:
/* assume 'Name' is a buffer 100 characters long */
scanf("%99s", baseStruct.Name);
这篇关于为什么这个C程序崩溃?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!