简体   繁体   English

用scanf和C中的字符串进行分段错误

[英]Segmentation fault with scanf and strings in C

I am a beginner with c, and I am having a problem with scanf and strings. 我是c的初学者,并且scanf和字符串有问题。

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");
}

basically, this code compiles, but when I run it I get a segmentation fault in strcmp() 基本上,这段代码可以编译,但是当我运行它时,我在strcmp()中遇到了段错误

if I replace the "string" in that line with "&string" it works, but I get this error from the compiler 如果我用“&string”替换该行中的“ string”,它可以工作,但是我从编译器中收到此错误

/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? 是我在这里找不到更好的解决方案,还是我唯一的选择?

thank you. 谢谢。

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

string is not pointing to any valid memory location. string未指向任何有效的内存位置。 Allocate memory using malloc to an array of characters and copy input to it. 使用malloc将内存分配给一个字符数组,然后将输入复制到该数组中。 Make sure allocated memory has space for null termination character. 确保分配的内存中有用于空终止符的空间。 Remember to free the memory to avoid leaks. 切记free内存以避免泄漏。

Just try that code 只需尝试该代码

     #include <stdio.h>
     #include <string.h>
     #include <stdlib.h>
     int main(void)
     {
       char* string;
       string=(char *)malloc(3); /*allocate the memory to string cahr pointer(default pointer point to single byte and if you print pointer variable don't used & character)*/                                                      
       scanf("%s", string);
       if (strcmp(string, "Foo") == 0)  
            printf("Bar\n");
     }

While declaring a char *. 同时声明一个字符*。 it will not having any memory location. 它不会有任何内存位置。 so you have to allocate a memory location before you use that variable. 因此,在使用该变量之前,您必须分配一个内存位置。 char *p; 字符* p; p=malloc(sieof(char) * size of string); p = malloc(sieof(char)*字符串大小);

then you use scanf() function. 然后使用scanf()函数。 it will work properly. 它会正常工作。

when we are accessing a unknown memory(ie unallocated memory). 当我们访问未知内存(即未分配的内存)时。 then it will through the segmentation fault 那么它将通过细分错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM