The compiler throws runtime segfault upon 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 please explain why string assignment does not work inside a struct which is dynamically allocated where in case of static allocation why it works ?
where as the following way it works :
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;
}
mallocjust allocates memory, it doesn't construct the object instance, which means thestringconstructor is not called.mallocin C++, usenew, and actually don't useneweither if possible, and usemake_sharedorstd::unique_ptr(C++11)