Created
May 8, 2012 21:15
-
-
Save AstDerek/2639351 to your computer and use it in GitHub Desktop.
String inside dynamically allocated struct
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <stdlib.h> | |
using namespace std; | |
typedef struct _node { | |
string name; | |
} node; | |
node *create_node () { | |
node *created; | |
created = (node *)calloc(1,sizeof(node)); | |
if (created) { | |
created->name = string(""); // Segmentation fault | |
} | |
return created; | |
} | |
int main (int narg, char *varg[]) { | |
node non_dynamic, *dynamic; | |
non_dynamic.name = "non_dynamic"; | |
cout << non_dynamic.name << endl; | |
dynamic = create_node(); | |
dynamic->name = "dynamic"; | |
cout << dynamic->name << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
created = (node *)calloc(1,sizeof(node));
needs to be replaced withcreated = new node;
and the error disappears