0

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) 
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
Bezzi
  • 260
  • 3
  • 15

2 Answers2

4

malloc() does not call the constructor of the std::string data, it's just a C function which allocates a chunk memory of specified size and the contents is random junk.

Therefore when you subsequently assign to the string, it does not just set the value like a plain variable does -- it calls function std::string::operator=, which tries to release any previous contents first, but that's not correct and it crashes.

You need to use C++ operator new to create the node instead, like so:

var = new node;

As you can see, you also don't need the ugly casts anymore.

Yirkha
  • 12,737
  • 5
  • 38
  • 53
  • This does not matter in his case - he sets all the fields of the `var` before using them. – mark May 08 '14 at 21:10
  • It does -- `var->data = value;` invokes `std::string::operator=`, which sees e.g. `0xdeadbeef` as its buffer pointer and calls `delete[]` on it -> crash. – Yirkha May 08 '14 at 21:14
  • @mark It does - the string in the node will not get constructed using 'malloc' –  May 08 '14 at 21:15
  • Oh, I missed that data was a C++ object. – mark May 08 '14 at 21:15
-1

I would say that you forgot to initialize head to NULL

mark
  • 59,016
  • 79
  • 296
  • 580