I am experimenting with C and trying to write a linked list. The LLCreateNode function is meant to return a pointer to a node allocated with malloc. However, after executing the call to LLCreateNode in main, tmp is still pointing to garbage that has nothing to do with the address returned by malloc and thus an error is milliseconds away.
I initially thought it may be because I cannot return a pointer from a function yet I found several examples with a similar implementation, one in C Programming by K&R. What is wrong? I am using NetBeans 6.8 with the GCC compiler included in Mac OS X.
Code:
int main(int argc, char** argv) {
struct Node* tmp = NULL;
struct LinkedList *list = NULL;
printf( "Declared the list" );
LLInitialize( &list );
printf("Initialized the list");
tmp = LLCreateNode( 10 );
LLAppendNode( &list, tmp );
printf( "Appended node" );
LLPrintList( list );
}
/*****Linked List Implementation*****/
#include "LinkedList.h";
int LLInitialize(struct LinkedList **list);
struct Node* LLCreateNode( int data );
int LLInitialize(struct LinkedList **list) {
(*list) = (struct LinkedList*)malloc(sizeof(struct LinkedList));
(*list)->head = NULL;
(*list)->tail = NULL;
if(*list == NULL)
return RT_FAIL;
return RT_SUCCESS;
}
struct Node* LLCreateNode(int data) {
struct Node *node = malloc(sizeof(struct Node));
node->data = data;
node->next = NULL;
return node;
}
int LLAppendNode(struct LinkedList **list, struct Node* node) {
if( (*list)->head == NULL ) {
(*list)->head = node;
(*list)->tail = node;
}
else
{
(*list)->tail->next = node;
(*list)->tail = node;
}
}