My task is to create program that reads all the words from file and puts into output file those words, that are identical from beginning to end (i mean aha, oho, asdsa, assa, etc). And task requires usage of dynamic memory (university), but I have been stuck in this place for days because I can't find why it doesn't want to do what I intend to do. I have 4 words in file. Those 4 printfs should print all words, but my program prints 3rd word, (null) and segmentation error. I use one-sided dynamic memory. Please explain why it doesn't work, because I can't do it myself. Thank you in advance! Code:
/*
* Task: Write program, that finds all words from file which reads from beginning to end (lets call them mirror-type words)
*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct elements
{
char str[255];
struct elements *next;
};
/* Function checks if given word is mirror-type word */
int is_mirror(char str[255])
{
int length = strlen(str);
int to = (length % 2 == 1) ? (length - 1) / 2 : length / 2;
int i = 0;
while (i < to)
{
if (str[i] != str[length-i-1]) return 0;
i++;
}
return 1;
};
int main()
{
FILE *in;
in = fopen("3_12.in", "r");
if (in == NULL)
{
printf("Input file doesnt exist.\r\n");
return 0;
}
char str[255];
fscanf(in, "%s", str);
struct elements *beginning, *element;
element = (struct elements *) malloc(sizeof(struct elements));
strcpy(element->str, str);
beginning = element;
do
{
fscanf(in, "%s", str);
element->next = (struct elements *) malloc(sizeof(struct elements));
strcpy(element->str, str);
if (feof(in))
{
element->next = NULL;
break;
}
}
while(1);
printf("%s\r\n", element->str);
printf("%s\r\n", element->next->str);
printf("%s\r\n", element->next->next->str);
printf("%s\r\n", element->next->next->next->str);
fclose(in);
}