Rafael Karele
Rafael Karele

Reputation: 3

My C program doesn`t work unless I add a printf before everything else

I tried to run the code and it terminates and doesn`t print anything, but if I include a printf statement as the first line in the main, it works. Why?

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

typedef struct node TNode;
typedef struct list TList;

struct list{
    TNode *node;
};

struct node{
    int data;
    TNode *next;
};

TList* buildList(){
    TList *list;
    list = (TList*)malloc(sizeof(TList));
    list->node->next = NULL;
    printf("\nList was built successfully\n");
    return list;
}


int main(){
    TList *myList = buildList();
    myList->node->data = 5;
    printf("\nData: %d\n", myList->node->data);
    return 0;
}

Upvotes: 0

Views: 254

Answers (1)

Venkatesh Nandigama
Venkatesh Nandigama

Reputation: 518

You are accessing list->node->next without having initialized list->node. Allocate memory for the node and assign a pointer to it to list->node.

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

typedef struct node TNode;
typedef struct list TList;

struct list{
    TNode *node;
};

struct node{
    int data;
    TNode *next;
};

TList* buildList(){
    TList *list;
    list = (TList*)malloc(sizeof(TList));
    list->node = (TNode*)malloc(sizeof(TNode));    // <---
    list->node->next = NULL;
    printf("\nList was built successfully\n");
    return list;
}


int main(){
    TList *myList = buildList();
    myList->node->data = 5;
    printf("\nData: %d\n", myList->node->data);
    return 0;
}

Upvotes: 1

Related Questions