嘿,我想知道是否有人知道如何解决这个问题。我想获取用户输入并从中执行一些操作。现在我在扫描线上发现了一个segfault,不知道为什么。在那之后,我试图将这两个数组连接在一起,这对我也很有帮助。
char command[1000];
char firstName[1000];
char lastName[1000];
char month[1000];
char day[1000];
while( strcmp("quit", &command[0]) != 0 ){
fflush(stdin);
printf("Please enter next command: ");
scanf("%s", command); // <--- This is tested and working
if(strcmp(&command[0], "quit") == 0){
break;
}
else if(strcmp(&command[0], "empty") == 0){
empty();
}
else if(strcmp(&command[0], "append") == 0){
printf("--------->1");
scanf("%s %s %s %s", firstName, lastName, month, day); //<--- This line :(
printf("--------->2"); // <---- This never prints
char fullName[2001];
char birthday[2001];
malloc(strlen(firstName) + 1);
strcpy(firstName, fullName);
malloc(strlen(lastName) + 1);
strcpy(lastName, fullName);
printf("%s", fullName);
从终端:
gregs-mbp:desktop GregR$ ./blist
Please enter next command: append greg r jan 02
Segmentation fault: 11
gregs-mbp:desktop GregR$ ./blist
Please enter next command: append
--------->1greg r jan 02
Segmentation fault: 11
gregs-mbp:desktop GregR$
gregs-mbp:desktop GregR$ ./bList
Please enter next command: quit
All done
最佳答案
你的代码中没有scanf的问题。问题出在代码上
char fullName[2001];
char birthday[2001];
malloc(strlen(firstName) + 1);
strcpy(firstName, fullName);
malloc(strlen(lastName) + 1);
strcpy(lastName, fullName);
printf("%s", fullName);
应该是这样的
char fullName[2001];
char birthday[2001];
strcpy(fullName,firstName);
strcat(fullName,lastName);
printf("%s", fullName);
工作程序示例:http://ideone.com/dvpHYL
我认为segfault是由
strcopy
的反向参数引起的。在fullName
中可能有一些任意数据(因为它以前没有初始化),当试图将其复制到firstName
时(它的大小较小),数据被写得超出了界限。malloc
s也不是必需的,但它们不应导致segfults,只会导致内存泄漏。关于c - 从scanf获取任意数量的参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22979642/