I am trying to create a linked-list with a string as the value inside each node, but every time I try to call the function that's supposed to add something to the list, it ends up giving me a segmentation fault error.
This is my code:
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
struct node
{
string data;
struct node *next;
}*head,*var,*trav;
void add(string value)
{
struct node *temp;
temp=head;
var=(struct node *)malloc(sizeof (struct node));
var->data = value;
if(head==NULL)
{
head=var;
head->next=NULL;
}
else
{
while(temp->next!=NULL)
{
temp=temp->next;
}
var->next=NULL;
temp->next=var;
}
}
int main(int argc, char const *argv[])
{
add("hello");
return 0;
}
It seems that the problem is in the var->data = value;
, but what exactly is causing it? And how could I fix that?
This is the error that shows up:
/bin/bash: line 1: 13056 Segmentation fault (core dumped)