For some reason I get problems in my structure, I believe its related to memory allocation For some reason, I get an error when running:
Segmentation fault (core dumped)
I understand that there might be some problem with memory allocation, but I can't detect the problem. I would like to know how to build it correctly and make it more stable. I’ve added comments to th code to make it clear
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
/* define the typedef struct node (self-referential structure) */
typedef struct node{
char data;
struct node *next
void print_linked_list(node *head){
unsigned int char_counter = 0;
node *temp = head;
/*iterate the entire linked list and print the data */
while(head->next != NULL){
++char_counter;
printf("%c", temp->data);
temp = temp->next;
if (char_counter%10==0){
******** */
/* this function walk the entire linked-list and free each node */
void free_linked_list(node* head){
while (head != NULL){
node *temp = head;
head = head->next;
free(temp);
}
return;
}
/* ********************************* Main ********************************** */
int main(int argc, char *argv[]){
char ch;
FILE *fog;
/* create the head of the linked list */
node *head = (node*)malloc(sizeof(node));
/* check if the memory allocation succeed */
if (!head){
printf("error 2: memory allocation failed\n");
exit(-2);
}
/* define the file descriptor*/
if (!(fd = fopen(argv[1], "r"))){
printf("error 1: cannot open the selected file.\n");
exit(-1);
}
/* read file char by char until reached EOF */
while ((character = fgetc(fd) != EOF)){
add_node(head, character);
}
print_linked_list(head);
free_linked_list(head);
if (fclose(fd)){
printf("error 3: close error\n");
exit (-3);
}
else {
printf("file closed successfully.\n");
}
return 0;
}