My program to compare strings fails with Segmentation Fault after the second input:
#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");
}
}
output:
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)
input
and input1
are uninitialized pointers. This causes to undefined behaviour (C language standard term).
You need to allocate meory using malloc()
or calloc()
. Or simply use local arrays:
char input[SIZE];
char input1[SIZE];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.