为什么这个C程序崩溃? [英] Why does this C program crash?

查看:116
本文介绍了为什么这个C程序崩溃?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经反复考虑这个了至少一个小时,我仍然无法找出问题所在。

 的#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函数需要写的的它),你给它一个未初始化的指针,可能指向任何地方。

考虑执行下列操作之一:


  1. 名称字符缓冲区,而不是:

      typedef结构
    {
        INT水平;
        CHAR名称[100];
    }基地;


  2. 从堆初始化:

      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:

  1. Make Name a character buffer instead:

    typedef struct
    {
        int Level;
        char Name[100];
    } Base;
    

  2. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆