簡體   English   中英

C上strcmp()中的分段錯誤

[英]Segmentation fault in strcmp() on C

我的比較字符串的程序在第二次輸入后由於“分段錯誤”而失敗:

#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)

inputinput1是未初始化的指針。 這會導致不確定的行為 (C語言標准術語)。

您需要使用malloc()calloc()分配malloc() 或者只是使用局部數組:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM