Segmentation fault assigning std::string in a struct

c++

Solution

Don't use `malloc` in C++ code, it's rarely the correct choice.

Your options are:

Token tok;
tok.val = "myval";

auto tok = std::make_unique<Token>(); // C++14
tok->val = "myval";

auto tok = std::unique_ptr<Token>(new Token()); // C++11
tok->val = "myval";

auto tok = std::make_shared<Token>(); // C++11, use if resource is shared
tok->val = "myval";

Token* tok = new Token();
tok->val = "myval";
delete tok;

These options should suffice for most cases.

Prefer the options from top to bottom: The default way should be creating objects, then `unique_ptr`, then `shared_ptr` and only if absolutely necessary you should deal with raw pointers.

The reason for that is easy: Exception safety and memory leaks. An object cannot be leaked, you can't forget to `delete` a `unique_ptr` or a `shared_ptr`, but you can with a raw pointer. Additionally, the raw pointer won't ever get deleted in case of an exception. `unique_ptr` should be preffered to `shared_ptr` because `shared_ptr` has overhead (an atomic counter to make it thread safe).

Demo that everything compiles fine (without C++14 make_unique): Demo

Problem

the following code results in a segmentation fault when it's run and I can't figure out why: ``` #include <cstdlib> #include <string> #include <iostream> using namespace std; struct Token { int num; string val; }; int main() { Token* tok = (Token*) malloc (sizeof(Token)); tok -> val = "myval"; std::cout<<tok->val; } ``` see backtrace: ``` 0 0x00007ffff7b95d9b in std::string::assign(char const*, unsigned long) () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6; 1 0x0000000000400867 in main () ```

Original source

Related problems