So I just started learning two weeks back and am basically a beginner. So I wrote this program. But it continuously gives Segmentation fault error line 41 in the strncat function. I am not sure what I am doing wrong.
#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;
}