文件分段错误(核心转储)(C-linux)
当我尝试运行这个时,我得到了一个分段错误(核心转储)。它编译得很好,但我得到了错误,我不知道为什么。文件写入一定有问题,因为如果没有它,效果会很好。任何帮助都会很好。谢谢文件分段错误(核心转储)(C-linux),c,linux,C,Linux,当我尝试运行这个时,我得到了一个分段错误(核心转储)。它编译得很好,但我得到了错误,我不知道为什么。文件写入一定有问题,因为如果没有它,效果会很好。任何帮助都会很好。谢谢 #include <stdio.h> #include <time.h> #include <unistd.h> #include <crypt.h> #include <string.h> int main(void) { FILE *f=fopen("shad
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <crypt.h>
#include <string.h>
int
main(void)
{
FILE *f=fopen("shadow1.txt","w");
if (f=NULL)
{
printf("ERROR");
}
unsigned long seed[2];
char salt[] = "$1$........";
const char *const seedchars =
"./0123456789ABCDEFGHIJKLMNOPQRST"
"UVWXYZabcdefghijklmnopqrstuvwxyz";
char *password;
int i;
/* Generate a (not very) random seed.
You should do it better than this... */
seed[0] = time(NULL);
seed[1] = getpid() ^ (seed[0] >> 14 & 0x30000);
/* Turn it into printable characters from ‘seedchars’. */
for (i = 0; i < 8; i++)
salt[3+i] = seedchars[(seed[i/5] >> (i%5)*6) & 0x3f];
/* Read in the user’s password and encrypt it. */
password = crypt(getpass("Password:"), salt);
/* Print the results. */
//fprintf(f,"%s $ %s",password);
printf("Success Registration to file !");
fclose(f);
return 0;
}
#包括
#包括
#包括
#包括
#包括
int
主(空)
{
文件*f=fopen(“shadow1.txt”,“w”);
如果(f=NULL)
{
printf(“错误”);
}
无符号长种子[2];
焦盐[]=“$1$……”;
常量字符*常量种子字符=
“/0123456789ABCDEFGHIJKLMNOPQRST”
“uvwxyzabcdefghijklmnopqrstuvxyz”;
字符*密码;
int i;
/*生成一个(不太)随机种子。
你应该做得比这更好*/
种子[0]=时间(空);
种子[1]=getpid()^(种子[0]>>14&0x30000);
/*将其从“seedchars”转换为可打印字符*/
对于(i=0;i<8;i++)
盐[3+i]=种子字符[(种子[i/5]>>(i%5)*6)&0x3f];
/*读入用户的密码并加密*/
password=crypt(getpass(“password:”),salt);
/*打印结果*/
//fprintf(f,“%s$%s”,密码);
printf(“成功注册到文件!”);
fclose(f);
返回0;
}
无效寄存器(char u,char p){
您可能希望它们是char*
,因为fprintf
将它们视为字符串:
fprintf(f,“%s$%s”,u,p);
既然您将char*
s传入:
char *password,*username;
//...
Register(username,password);
这很可能被编译器警告捕获。从编译器获取答案要比从这里快速得多
如果您无法找出程序无法运行的原因,您可以使用
-Wall-Wextra
启用所有需要的警告,并使用-Werror
将警告转换为错误。您没有分配空间来保存用户名,因此它将在scanf上出现故障
if (f=NULL)
{
printf("ERROR");
}
问题是…你的调试器告诉你什么?它是在linux中,所以我没有调试器…
sudo apt install gdb
应该可以解决这个问题。用-g
选项编译(并链接)你的程序。不要运行“/myprogram
”,而是运行“gdb myprogram
”。键入“run
”。您的程序将运行,并希望以相同的方式崩溃。键入“bt
”(回溯)。gdb将向您显示程序崩溃的确切位置。通常这足以解决问题。“lab3.c:46:59:警告:传递'crypt'的参数2会使指针从整数开始,而无需强制转换[-Wint conversion]password=crypt(getpass(”创建密码:“)、s);“等等,crypt的签名是什么?您是否更改了主函数和实现中的转发声明?是的……我编辑了一些警告,如果它们可以帮助的话。他说的是您需要一个缓冲区并传递所述缓冲区的地址。char buf[];scanf(%79s),buf);我输入了注释username,以查看这是否是问题所在,但错误仍然存在……您也没有为密码分配内存,除非您的crypt函数正在执行此操作。与其他注释一样,如果f=null错误,它会将null分配给f,而不是检查其值,请使用==进行比较。