How to use a C++ string in a structure when malloc()-ing the same structure?
You can't malloc
a class with non-trivial constructor in C++. What you get from malloc
is a block of raw memory, which does not contain a properly constructed object. Any attempts to use that memory as a "real" object will fail.
Instead of malloc
-ing object, use new
example *ex = new example;
Your original code can be forced to work with malloc
as well, by using the following sequence of steps: malloc
raw memory first, construct the object in that raw memory second:
void *ex_raw = malloc(sizeof(example));
example *ex = new(ex_raw) example;
The form of new
used above is called "placement new". However, there's no need for all this trickery in your case.
Segmentation fault on using std::string inside a dynamically allocated struct
malloc
is not suitable for creating non-POD objects. It allocates memory but does not call any constructors. So your line a->a1
accesses a string that has not yet been constructed, causing undefined behaviour.
To properly allocate and construct the object use:
a = new A;
It is bad style (at best) to use malloc
in any C++ program
C - how to malloc struct containing string and array?
When you allocate space for your struct as Node *new_node = malloc(sizeof(Node));
, that includes space for each struct element.
In this case, that includes space for 32 char
and 10 int *
. So you don't need to allocate space for the name
array, although depending on your usage, you might allocate space to each element of contents
.
String in struct
C++ is not C.
You shouldn't #include
anything from the bits
folder.
You should not use malloc
to allocate memory. You should use new
instead:
node* p = new node();
Or just don't dynamically allocate memory at all:
node p;
C++ is not C.
C++ code crashing when trying to pass struct
Don't use malloc
in C++.
If you need a variable to have dynamic storage duration, use new
and delete
instead. In short, malloc
will not call any constructors, whereas new
will. The fact that the std::string
constructor is not being called is probably the cause of your crash.
In many cases though, automatic storage duration will suffice, and you can write, simply:
dat foo;
and pass that instance by reference to your functions.
Getting exceptions thrown within string library
You are using malloc on a structure that contains a C++ class member (std::string in this case). This is a problem because C++ object construction isn't going to happen. Generally, you'd want to use the new
operator instead of calling malloc in C++.
Segmentation fault assigning std::string in a struct
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
Related Topics
How to Output Coloured Text to a Linux Terminal
What's the Difference Between _Pretty_Function_, _Function_, _Func_
Using Opencv and Svm With Images
How Does #Include ≪Bits/Stdc++.H≫ Work in C++
What Are the Gcc Default Include Directories
How to Call a Base Class'S Virtual Function If I'M Overriding It
Determine the Line of Code That Causes a Segmentation Fault
How Can a Windows Service Execute a Gui Application
Variable Initialization in C++
How to Output a Character as an Integer Through Cout
How Could Pairing New[] With Delete Possibly Lead to Memory Leak Only
Comparing a Variable to a Range of Values
Getting Size of Array from Pointer C++
What Open Source C++ Static Analysis Tools Are Available
How to Avoid Memory Leaks When Using a Vector of Pointers to Dynamically Allocated Objects in C++