从用户读取输入时,fgets分段错误 [英] fgets segmentation fault when reading input from user

查看:81
本文介绍了从用户读取输入时,fgets分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是使用ubuntu的令人反感的代码

here's the offending code using ubuntu

char *name;

int main(void)
{
  fgets(name, sizeof(name), stdin);
}
void HUD()
{
  printf("%s ", name); 
}

这是我的问题.我从scanf(%s",& name)开始,并且在字符串末尾变得垃圾.在过去的两个小时中,一直在阅读有关scanf和fgets的文档,因为当您不知道所需数组的大小时(并且由于用户输入的大小可能会有所不同),显然不应该使用scanf,所以我决定尝试使用fgets.我也尝试通过char name [100]设置一个固定值.和fgets(name,100,stdin)

Here's my problem. I started with scanf("%s", &name) and was getting junk at the end of the string. Through the last 2 hours have been reading docs on scanf, and fgets, because apparently scanf shouldn't be used when you don't know the size of the array you want, (and since user input can vary in size) I decided to try using fgets. I've also tried setting a fixed value both by char name[100]; and by fgets(name, 100, stdin)

现在,我遇到了细分错误,通过阅读我在google的前2页中发现的每个结果,我的语法似乎正确,并且在cboard或此处都找不到任何解决方法.

Now I'm getting a segmentation fault, and through reading every result I found on the first 2 pages of google, my syntax appears correct, and I've found nothing on cboard or here to fix my problem.

有什么想法吗?

推荐答案

sizeof(name)将是系统上指针的大小,在我看来是8个字节.不是您期望的那样,缓冲区的大小

sizeof(name) Will be the size of the pointer on your system, on mine it's 8 bytes. Not the size of the buffer, as you might have been expecting

char *名称也未初始化.您将尝试写入未初始化的缓冲区,并且它将以未定义的行为结束.

Also char* name is uninitialised. You will try to write to an uninitialised buffer and it will end in undefined behaviour.

要解决该问题,可以将其设置为固定大小的缓冲区,或者在堆上分配一些空间.

To resolve either make it a fixed size buffer or allocate some space on the heap.

分配

#include <stdio.h>
#include <stdlib.h>

#define NAME_SIZE 100
char *name;

void HUD()
{
  printf("%s ", name); 
}

int main(void)
{
    name=calloc(NAME_SIZE, sizeof(char));
    fgets(name, NAME_SIZE, stdin);

    HUD();

    free(name);
}

静态数组

#include <stdio.h>
#include <stdlib.h>

#define NAME_SIZE 100
char name[NAME_SIZE];

void HUD()
{
  printf("%s ", name); 
}

int main(void)
{
    fgets(name, NAME_SIZE, stdin);

    HUD();
}

您必须将缓冲区的大小传递给 fgets ,以便它知道必须写入多少空间.

You must pass the size of the buffer to fgets so it know how much space it has to write in to.

这篇关于从用户读取输入时,fgets分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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