【问题标题】:Segmentation fault in strcmp() on CC 上 strcmp() 中的分段错误
【发布时间】:2014-02-24 00:25:19
【问题描述】:

第二次输入后,我比较字符串的程序因分段错误而失败:

#include<stdio.h>

#include<string.h>

int main (void)

{       
    char* input1;
    char* input2;
    printf("type something: ");
    scanf("%s", &input1);

    printf("type something: ");
    scanf("%s", &input2);

    if(strcmp(input1, input2) == 0)
    {
        printf("u type the same thing\n");  
    }
    else
    {
        printf("u not type the same thing\n");
    }

}

输出:

sekai92@sekai92-VirtualBox:~/Desktop/C_CPP$ make compare
clang -Wall -Werror -ggdb     compare.c   -o compare
sekai92@sekai92-VirtualBox:~/Desktop/C_CPP$ ./compare 
type something: hello
type something: hello
Segmentation fault (core dumped)

【问题讨论】:

  • char *input1 = (char *)malloc(64 * sizeof(char));
  • 这一定是我以前不知道的“作品”的新定义。

标签: c pointers scanf


【解决方案1】:

inputinput1 是未初始化的指针。这导致undefined behaviour(C 语言标准术语)。

您需要使用malloc()calloc() 分配内存。 或者干脆使用本地数组:

char input[SIZE]; 
char input1[SIZE];

【讨论】:

    猜你喜欢
    • 2015-08-14
    • 2011-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    • 2020-08-25
    相关资源
    最近更新 更多