【发布时间】:2016-08-03 17:14:26
【问题描述】:
所以我两周前才开始学习,基本上是个初学者。所以我写了这个程序。但它在 strncat 函数中不断给出 Segmentation fault 错误行 41。我不确定我做错了什么。
#include <stdio.h>
#include <string.h>
#define _XOPEN_SOURCE
#include <unistd.h>
#define _GNU_SOURCE
#include <crypt.h>
#define WORD "/usr/share/dict/words"
int error(void);
int check(char *text, char *psswrd, char *salt);
int main(int argc, char *argv[])
{
if (argc != 2)
return error();
char salt[3];
salt[0] = argv[1][0];
salt[1] = argv[1][1];
salt[2] = '\0';
FILE *fptr;
char ch;
char *word;
int flag = 0;
fptr = fopen(WORD, "r");
if (fptr == NULL)
{
flag = 1;
}
else
{
do
{
ch = fgetc(fptr);
if ( ch != ' ' && ch != '\n')
{
word = strncat(word, &ch, 1);
if (strlen(word) == 8)
{
flag = check(word, argv[1], salt);
if (flag == 0)
{
printf ("%s \n", word);
return 0;
}
}
}
else
{
word = "";
}
}
while (ch != EOF);
fclose(fptr);
}
if (flag == 2)
{
printf("Password not found\n");
return 2;
}
}
int error(void)
{
printf ("Usage: ./crack <encrypted keyword>\n");
return 1;
}
int check(char *text, char *psswrd, char *salt)
{
if (strcmp(crypt(text, salt), psswrd) == 0 )
return 0;
else
return 2;
}
【问题讨论】:
-
你需要为
word分配内存。 -
加一行
word = (char *) malloc(<memsize>); -
要使
ch == EOF工作,ch必须是int,而不是char。但是,如果您将其设为int,您将无法将其用作strncat的参数。 (在我看来,这并不重要。strncat是一种将字符附加到长度已知的字符串的可怕方法。) -
@rici 这是我现在知道的唯一方法。
标签: c segmentation-fault