C中scanf和字符串的分段错误 [英] Segmentation fault with scanf and strings in C

查看:29
本文介绍了C中scanf和字符串的分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 c 初学者,但我遇到了 scanf 和字符串的问题.

I am a beginner with c, and I am having a problem with scanf and strings.

这是我写的一个关于我的问题的例子.

here is an example I wrote of my problem.

#include <stdio.h>
#include <string.h>

int main(void)
{
    char* string;
    scanf("%s", &string);
    if (strcmp(string, "Foo") == 0)  //segmentation fault here
        printf("Bar");
}

基本上,这段代码可以编译,但是当我运行它时,我在 strcmp() 中遇到了分段错误

basically, this code compiles, but when I run it I get a segmentation fault in strcmp()

如果我将该行中的字符串"替换为&string",它可以工作,但我从编译器收到此错误

if I replace the "string" in that line with "&string" it works, but I get this error from the compiler

/usr/include/stdio.h:362:12: note: expected 'const char * __restrict__' but argument is of type 'char **'

这让我觉得这个解决方案并不理想.

which makes me think that this solution is not really ideal.

如果我这样声明字符串:

also If I declare string like this:

char string[100];

它可以在没有任何警告的情况下工作,但这也不理想,因为我不确定字符串会有多大.

that works without any warnings, but that is also not ideal because I am not sure how large the string is going to be.

我在这里缺少更好的解决方案吗,或者这些是我唯一的选择吗?

Is there a better solution I'm missing here, or are these my only options?

谢谢.

推荐答案

char* string;
scanf("%s", &string);

string 没有指向任何有效的内存位置.使用 malloc 将内存分配给字符数组并将输入复制到其中.确保分配的内存有空终止字符的空间.请记住释放内存以避免泄漏.

string is not pointing to any valid memory location. Allocate memory using malloc to an array of characters and copy input to it. Make sure allocated memory has space for null termination character. Remember to free the memory to avoid leaks.

这篇关于C中scanf和字符串的分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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