1

Im triying to compile and execute this small c++ code using g++ 5.1, it's compiled fine, when i execute it on linux i get this error message : "Segmentation fault (core dumped)".

But the same code run correctly on osx but not on linux :

#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <string.h>
using namespace std;

struct node {
 std::string data;
};

int main() {
  struct node * node = (struct node * )
  malloc(sizeof(struct node));

  node->data.assign("string");
  // node->data = "string" --> same issue

  return 0;
}

i tried a simple assigne (node->data = "string"), but i got the same problem Any help please !

Christophe
  • 68,716
  • 7
  • 72
  • 138
AHmedRef
  • 2,555
  • 12
  • 43
  • 75
  • 5
    Why are you using `malloc` in C++ code? `new` will initialise the string object - `malloc` does not. – Ed Heal Jul 16 '16 at 20:36
  • 1
    Who keeps teaching stuff like this? Does it not occur to those people that the 80s are over? :/ – Baum mit Augen Jul 16 '16 at 20:37
  • 1
    To expand on what @EdHeal said: it's not enough to just allocate sizeof(struct node) bytes and then start using them. You have to make sure the string object's constructor runs also, so that the node object's private state will be initialized correctly. In order to do that you need to use the new operator (e.g. node = struct node * node = new node; ) – Jeremy Friesner Jul 16 '16 at 20:38
  • Btw, have a look at the linked question, it's probably not quite a dupe, but highly related at least. – Baum mit Augen Jul 16 '16 at 20:44
  • `C++` programs are not "scripts". – Galik Jul 16 '16 at 20:48
  • @EdHeal and Jermy thank's it's worked now after using new :) – AHmedRef Jul 16 '16 at 20:49
  • @Galik so what is called ? – AHmedRef Jul 16 '16 at 20:49
  • @AHmédNet Its generally referred to as "code". For example "some code", "this code". "I wrote some code", "I have some code". "A piece of code" etc – Galik Jul 16 '16 at 20:52
  • @AHmédNet Scripts are technically different: https://en.wikipedia.org/wiki/Scripting_language ALSO http://www.computerhope.com/jargon/s/script.htm – Galik Jul 16 '16 at 20:53
  • @Galik thank's im gonna changing script by code :) – AHmedRef Jul 16 '16 at 20:54
  • 1
    And in programming "code" is *never* pluralized using an 's'. You would *never* say "codes". (When people do that it's grammatically incorrect) – Galik Jul 16 '16 at 20:55

2 Answers2

5

With C++ forget about malloc(). If you want to allocate an object use new:

node * n = new node;   // or if your variable should be called node 
                       // you'd need new struct node to disambiguate

The problem with malloc() is that it just allocates uninitialized memory. It doesn't ensure the C++ semantic of object creation. So the string inside your node is not initilized to a valid state. This causes the assignment of this string to be UB.

If you'd really need to use malloc() in C++, you'd need to use a placement new afterwards to initialize the object to a valid state (online demo).

 void *p = malloc(sizeof(node));   // not so a good idea ! 
 node *n2 = new (p)node;           // but ok, it's feasible. 
Christophe
  • 68,716
  • 7
  • 72
  • 138
  • Why does the string has to be initialized since he is replacing what ever its there with "string" ... also how does the new make sure the constructor of string is called? – solti Jul 16 '16 at 21:06
  • 3
    @solti That's what `new` does, it allocates memory and calls the constructor. – Hatted Rooster Jul 16 '16 at 21:08
  • 1
    @GillBates since string is not constructed ( because constructor not called for string) that is why the segfault? – solti Jul 16 '16 at 21:10
  • 2
    @solti Yes, it's undefined behaviour to just pretend the allocated memory is a string object and use it as one – Hatted Rooster Jul 16 '16 at 21:11
  • Note that using placement new requires the programmer to explicitly call the object's destructor too at the end of it's lifetime. – Hatted Rooster Jul 16 '16 at 21:14
  • @GillBates about destruction afeter a placement new you are of course vey wise to remind it. For AHméd Net: detailed explanation in the link to the placement new article. – Christophe Jul 16 '16 at 21:22
  • @GillBates I found this link which is similar to our discussion ... http://stackoverflow.com/questions/2995099/malloc-and-constructors – solti Jul 16 '16 at 21:59
  • @AHmédNet you might want to accept anyone of the answers – solti Jul 16 '16 at 22:00
5

You can't malloc a C++ string. You should be using proper new and delete, at least, so that constructors are invoked. Stop using C in C++.

Ideally you wouldn't even use new; just have a normal object with automatic storage duration or, if you desperately need dynamic allocation, std::make_unique.

There is no need for manual memory management in 2016.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055