Skip to content

Instantly share code, notes, and snippets.

@AstDerek
Created May 8, 2012 21:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AstDerek/2639351 to your computer and use it in GitHub Desktop.
Save AstDerek/2639351 to your computer and use it in GitHub Desktop.
String inside dynamically allocated struct
#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;
}
@AstDerek
Copy link
Author

AstDerek commented May 8, 2012

created = (node *)calloc(1,sizeof(node)); needs to be replaced with created = new node; and the error disappears

@thomas861205
Copy link

omg you are my savior

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment