The standard C function malloc
allocates raw memory knowing nothing about the object that will be placed in the memory.
So neither constructor of the object will be called.
The structure Node contains data member of the type std::string
for which a constructor shall be called.
In C++ use the operator new
instead of calling the C function malloc
. The operator not only allocates memory but also calls a constructor for the created object.
It is a bad idea to use global objects in function definitions without passing them through parameters.
The function display
can have an infinite loop in case when head
is not equal to null pointer because the variable ptr
(that is assigned with head) used in the loop is not changed.
void display()
{
struct Node* ptr;
ptr = head;
while (ptr != NULL) {
std::cout << ptr->s << std::endl;
}
}
The function insert can be called only once
void insert(const std::string& name)
{
struct Node* newnode = (struct Node*)malloc(sizeof(struct Node));
newnode->s = name;
newnode->next = NULL;
head = newnode;
}
because otherwise it can result in memory leaks
You should free nodes before exiting the program.
Here is a modified your program that does not have the drawbacks of the original program.
#include <iostream>
#include <string>
struct Node
{
std::string s;
Node *next;
};
void insert( Node * &head, const std::string &s )
{
head = new Node { s, head };
}
std::ostream & display( const Node * head, std::ostream &os = std::cout )
{
for ( const Node *current = head; current != nullptr; current = current->next )
{
os << current->s << '\n';
}
return os;
}
void clear( Node * &head )
{
while ( head )
{
Node *tmp = head;
head = head->next;
delete tmp;
}
}
int main()
{
Node *head = nullptr;
insert( head, "Jimmy" );
display( head );
clear( head );
return 0;
}
Its output is
Jimmy