Cesa Salaam
Cesa Salaam

Reputation: 77

Why is there junk data in the first node of my linked list?

It appears that there is junk data in the first node of my list. Why would this be?

These are the definitions of the structs i'm using.

typedef struct node { 
   char *x; 
   struct node *next; 
}node;

typedef struct { 
   struct node *head;
}list;

// create_list() function :

list* create_list(){
    list *myList = malloc(sizeof(myList));
    myList->head = NULL;
    if (myList->head != NULL){ 
       return NULL; 
    }
    return myList; 
 }

Here is the implementation of the add_to_list function

int add_to_list(list* ll, char* item){

    node *current = ll->head;
    node *new_node = malloc(sizeof(node));
    if (!new_node){
        fprintf(stderr, "error allocating mem.\n");
        return 1;
    }
    strcpy(new_node->x, item);
    new_node->next = NULL;
    if(ll->head == NULL){
       ll->head = new_node;
       return 0;
    }else{
       while(current->next){
       current = current->next;
    }
     current->next = new_node;
   }
  return 0;
}

This is the print_list(); funcntion

void print_list(list *ll){

    node *current = ll->head;
    while(current){
       printf("%s\t\n",current->x);
       current = current->next;
    }
}

when I call the function in main.c here is how i'm doing it :

list *newList = create_list();

char test_var = 'k';

add_to_list(newList, &test_var);

printf("printing whole list : \n");

print_list(newList);

Upvotes: 0

Views: 112

Answers (2)

user3629249
user3629249

Reputation: 16540

regarding this statement:

strcpy(new_node->x, item);

the 'x' field is a uninitialized pointer. so using that pointer to point to the destination area is undefined behavior.

Writing to where a uninitialized pointer points could result in a seg fault event.

AND is the reason for the corrupted data. Your just lucky a seg fault didn't occur nor any of the other data being corrupted.

if you know the max length of the data, then you could change the struct definition so the field 'x' is an array of char rather than a pointer.

Otherwise, suggest using something similar to:

new_node->x = strdup( data );
if( !new_node->x )
{ // then strdup() failed
    perror( "strdup failed" );
    // call a cleanup function here
    free( new_node );
    exit( EXIT_FAILURE );
}

// implied else, strdup successful

Upvotes: 0

Mitch
Mitch

Reputation: 3418

It is because you are passing a char as a char pointer (ie a string). Change

char test_var = 'k'; 

to

char *test_var = "k";

and change the call to

add_to_list(newList, &test_var)

to

add_to_list(newList, test_var)

Upvotes: 3

Related Questions