永发信息网

Segmentation fault怎么解决

答案:2  悬赏:0  手机版
解决时间 2021-03-29 08:37
  • 提问者网友:回忆在搜索
  • 2021-03-28 11:49
Segmentation fault怎么解决
最佳答案
  • 五星知识达人网友:话散在刀尖上
  • 2020-04-19 20:12
出现段错误/非法内存访问可能是因为:
你读的时候读的长度和你的输入有关,而实际上存在文件中的用户名密码长度不一定是你输入的长度。这时候(比如少读或多读一个字符),那么你的fgetc让文件指针移动之后就不会停在你想要的地方。发生错误最好的解决办法是调试。无论是简单的加printf语句,或是添加断点进行观察都是不错的选择。
下面是我调好的一个版本,其中有些变量名称进行了修改更方便理解。(另外我假设密码不一定是一个数字,而可能也是一个字符串)

#include 
#include 
#include 

int main()
{
   char usrName[100], usrPwd[100], curName[100], curPwd[100];
   int n = 0;

FILE* fp = fopen("UserInfo.txt", "r");

if (!fp) {
   printf("UserInfo.txt missing...\n");
   return 0;
}

printf("User login:\n\nUsername: ");
scanf("%s", usrName);
printf("Password: ");
scanf("%s", usrPwd);
printf("\n");


while(!feof(fp))
    {
fscanf(fp, "%s", curName);
fscanf(fp, "%s", curPwd);

     if (strcmp(usrName, curName) == 0 && strcmp(usrPwd, curPwd) == 0)
     {
         printf("Login Successfully");
         n = 1;
break;
     }
    }

    fclose(fp);

if (n == 0)
{
      printf("Login failure");
}

return 0;
}
简单测试之后我这边暂时是没什么问题……有问题欢迎讨论。

排版出错的话自己再弄一下吧。
全部回答
  • 1楼网友:大漠
  • 2020-06-14 22:44
#include #include int main(void) { char s[25]="####"; char d[256]="this is a test for memcpy"; char *ptr = null; printf("destination before memcpy: %s\n",d); ptr=memcpy(d,s,strlen(s)); if(ptr) printf("destination after memcpy: %s\n",d); else printf("memcpy failed\n"); return 0; } 数组对应着一块内存区域,而指针是指向一块内存区域。其地址和容量在生命期里不会改变,只有数组的内容可以改变;而指针却不同,它指向的内存区域的大小可以随时改变,而且当指针指向常量字符串时,它的内容是不可以被修改的,否则在运行时会报错。 memcpy(3) linux programmer鈙 manual memcpy(3) name memcpy - copy memory area synopsis #include void *memcpy(void *dest, const void *src, size_t n); description the memcpy() function copies n bytes from memory area src to memory area dest. the memory areas should not overlap. use memmove(3) if the memory areas do overlap.
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯