A Struct containing a string value causes a segmentation error after it is assigned after it has been created using dynamic memory allocation

The compiler issues a runtime segfault with the following code:

#include <iostream> #include <string> using namespace std; struct Node{ int data; void *next; string nodeType; }; Node* initNode(int data){ Node *n = (Node*)malloc(sizeof(Node)); n->data = data; n->next = NULL; n->nodeType = "Node"; //if this line is commented it works else segfault return n; } int main() { Node *n1 = initNode(10); cout << n1->data << endl; } 

Can someone explain why the purpose of the line does not work inside the structure that is dynamically allocated, where in the case of static distribution, why does it work?

where as follows:

 Node initNode(string data){ Node n; n.data = data; //This works for node creation statically n.next = NULL; n.nodeType = "Node"; //and even this works for node creation statically return n; } 

and then in the main function:

 int main() { Node n2 = initNode("Hello"); cout << n2.data << endl; } 
+6
source share
4 answers

This does not work because you are not actually creating an instance of Node in the memory you malloc .

Instead, use new :

 Node *n = new Node{}; 

malloc only allocates memory; it does not know what a class is or how to create it. Normally you should not use it in C ++.

new allocates memory and instantiates the class.

+8
source

There is no place where the constructor std :: string is executed.

You must use new

 example *e = new example; 

or posting a new

 void *example_raw = malloc(sizeof(example)); example *e = new(example_raw) example; 
+4
source
  Node *n = (Node*)malloc(sizeof(Node)); 

This tide is nonsense. You cannot just tell the compiler to pretend that the piece of data you just allocated contains a valid Node object and then manages it.

+3
source

string in C ++ is a class and to create string objects use new instead of malloc, as shown below.

 Node *n = new Node{}; 
+1
source

Source: https://habr.com/ru/post/983900/


All Articles