为什么在一切都正确完成后,我在应用程序结束时会出现段错误?
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
unsigned char *stole;
unsigned char pass[] = "m4ak47";
printf("Vnesi password: \t");
scanf("%s", stole);
if(strncmp(stole, pass, sizeof(pass)) != 0)
{
printf("wrong password!\n");
exit(0);
}
else
printf("Password correct\n");
printf("some stuf here...\n\n");
return 0;
}
这个程序运行良好,但有一个问题 - 如果密码正确,那么它确实会打印“这里有一些东西......”,但它最后还显示了分段错误错误。为什么 ?
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
unsigned char *stole;
unsigned char pass[] = "m4ak47";
printf("Vnesi password: \t");
scanf("%s", stole);
if(strncmp(stole, pass, sizeof(pass)) != 0)
{
printf("wrong password!\n");
exit(0);
}
else
printf("Password correct\n");
printf("some stuf here...\n\n");
return 0;
}
This program is working nice, but with one problem - if the password is correct then it DOES do the printing of 'some stuf here...' but it also shows me segmentation fault error at the end. Why ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
unsigned char *stole;
上面的语句将
stole
声明为指向unsigned char
的指针,并包含垃圾值,指向某个随机内存位置。scanf("%s", 偷);
上面的语句尝试将一些字符串存储到由另一个程序使用的
stole
指向的内存中(至少没有分配给您的程序使用)。因此,当scanf
尝试覆盖此内存时,您会得到seg-fault
。尝试将内存分配给
stole
,如下所示unsigned char stole[MAX_SIZE];
或
动态字符串输入
unsigned char *stole;
The above statement declares
stole
as a pointer tounsigned char
and contains garbage value, pointing to some random memory location.scanf("%s", stole);
The above statement tries to store some string to memory pointed by
stole
which is being used by another program (atleast not allocated to your program for use). So, whenscanf
attempts to over-write this memory, you getseg-fault
.Try to allocate memory to
stole
as followsunsigned char stole[MAX_SIZE];
or
Dynamic String Input
stole 是一个悬空指针 - 您需要为其分配一些内存(例如 malloc)
stole is a dangling pointer - you need to allocate some memory for it (e.g. malloc)
您必须为
stole
提供存储空间,例如:如果用户输入的字符串超过 1024 个字符,这仍然会产生段错误,要解决此问题,您可以使用:
使用 1023 而不是 1024这样就有空间容纳字符串终止符。
You have to supply the storage for
stole
, something like:This will still give a segfault if the user enters a longer string than 1024 chars though, to fix this you can use:
1023 is used instead of 1024 so that there's room for the string terminator.