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; }
source share