0

I have a small problem with my code and hope you can help me. This program below reads names that are written in a txt-file and stores them in a linked list and prints them back out on the command line.

The list consists of the following names:

Gustav Mahler
Frederic Chopin
Ludwig van Beethoven
Johann-Wolfgang Von-Goethe

But when I run the program, the execution of the program is interrupted, either before printing the list or after.

If I remove the last line it works perfectly, but when I add it back in to the list or replace it with a random combination like "jlajfi3jrpiök+kvöaj3jiijm. --aerjj" it stops again.

Can somebody please explain to me why the program execution gets interrupted?

Thank you in advance ! :)

Here's the Program:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct list {
    char* name;
    struct list *next;
}NODE;

char * getString(char *source);

int main() {

FILE *fpointer = NULL;              
char filename[100];

puts("\nEnter the name of the file:\n");
gets(filename);

if((fpointer = fopen(filename, "r")) == NULL ) {
    printf("\nThe file you have chosen is not valid.\n");
    return 1;
}

char buffer[200];
NODE *head = NULL;
NODE *current = NULL;


while(fgets(buffer, 200, fpointer) != NULL) {

    NODE *node = (NODE *) malloc(sizeof(NODE));                         
    node -> next = NULL;

    node -> name = getString(buffer);


    if(head == NULL) {
        head = node;
    } else {
        current -> next = node;
    }

    current = node;

}

current = head;
while(current) {
    printf("%s", current -> name);
    current = current -> next;
}


return 0;
}


char * getString(char* source) {
    char* target = (char*) malloc(sizeof(char));
    strcpy(target, source);
    return target;
}
serene
  • 11
  • 1
    `malloc(sizeof(char))` allocates **1 byte**, only enough for a string terminator! Suggest `char* target = malloc(strlen(source) + 1));` or even `char* target = strdup(source);` – Weather Vane Feb 27 '18 at 20:55
  • Please read [Why is the gets function so dangerous that it should not be used?](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) – Weather Vane Feb 27 '18 at 21:01

1 Answers1

0

In getString, you're not allocating enough space for the string you want to copy:

char* target = (char*) malloc(sizeof(char));

This is only allocating space for a single character. You need enough for the length of the string, plus 1 more for the null terminating byte:

char* target = malloc(sizeof(strlen(source) + 1);

You could actually replace the entire function with a call to strdup, which does the same thing.

Also, don't cast the return value of malloc, and never use gets.

dbush
  • 205,898
  • 23
  • 218
  • 273