mrtammy
mrtammy

Reputation: 217

C++ linked list not displaying String type variables

I have a string variable named flavour under my struct Node, every time I enter the string for flavour variable the program stops working and ends up printing nothing. I have tested it out by using different variable types such as integer and character, both variable type works just fine and will print out whatever is in the variable.

Here is my code:

#include <iostream>
using namespace std;
struct Node { 
   string flavor;
   struct Node *next; 
}; 
struct Node* head = NULL;   
void insert(string data) { 
   struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); 
   new_node->flavor = data; 
   new_node->next = head; 
   head = new_node; 
} 
void display() { 
   struct Node* ptr;
   ptr = head;
   while (ptr != NULL) { 
      cout<<"First data is "<< ptr->flavor; 
      ptr = ptr->next; 
   } 
} 
int main() { 

    string input;
    cout<<"Enter a flavor!"<<endl;
    cin>>input;
    insert(input);

   cout<<"The linked list is: ";
   display(); 

   return 0; 
} 

Here is the result, as you can see everything after cin>>input; or insert(input) doesn't seem to work. Am I missing out on something? Result

Upvotes: 0

Views: 230

Answers (2)

robthebloke
robthebloke

Reputation: 9678

Allocate with new instead of malloc. Currently your code leaves the string Node::flavour in an uninitialised state, so when you attempt to assign a value to it, it is attempting to free or access an invalid memory location.

Node* new_node = new Node;

Upvotes: 3

Ali Tavakol
Ali Tavakol

Reputation: 439

With malloc, class constructor doesn't get called. Use new instead.

Upvotes: 3

Related Questions