Search code examples
cdynamiclinked-list

Linked list refuses to work with dynamiclly allocated buffer but works with static allocation


I've tried making a linked list with a dynamic allocated buffer but it just screws the program and exit.

for some reason, the program works perfectly with static buffer which is more perplexing to me.

I've checked that the memory allocation in fact does allocate and checked that the size of the memory is appropriate.

typedef struct game_node {
    char* title;
    char* genre;
    int year;
    float rating;
    struct game_node* next;
    struct dlc_node* dlc_head;
}GameNode;

typedef struct dlc_node {
    char* title;
    float price;
    struct dlc_node* next;
}DLCNode;

typedef struct {
    GameNode* head;
}GameLinkedList;

This is the function in which it gets stuck.

GameNode* GameAdd(){
    GameLinkedList *gm;
    char *buffer = malloc(256*sizeof(char));
    
    GameNode *newNode = (GameNode*)malloc(sizeof(GameNode));
    if(newNode == NULL){return NULL;}
    newNode = gm->head;

    //Get Input from user

    printf("Game Title - ");
    scanf("%s",buffer);
    
    newNode->title = (char *)malloc(strlen(buffer) + 1);
    
    if(newNode->title == NULL){
        free(newNode->title);
        free(newNode);
        exit(1);
    }
    
    
    strcpy(newNode->title,buffer);
    //stops after this strcpy
    
    
    printf("Game Genre - ");
    scanf("%s",buffer);
    
    newNode->genre = (char *)malloc(strlen(buffer) + 1);
    if(newNode->genre == NULL){
        free(newNode->genre);
        free(newNode->genre);
        free(newNode);
        exit(1);
    }
    strcpy(newNode->genre,buffer);
}

Solution

  • GameLinkedList *gm;
    ...
    newNode = gm->head;
    

    Problem: gm is used uninitialized in the assignment to newNode.

    Aside:

    • Check the return of malloc(3).
    • Don't cast the result of malloc(3). malloc(3) and family returns a generic void * that is implicitly converted to any other pointer type. Casting only serves to clutter one's code.
    • Don't pass NULL pointers to free(3), or the same argument twice. The former is not an error per se, but the latter is sure to result in one.
    • Use a field-width specifier with scanf(3). Or Consider using fgets(3) instead.