c - Seg Fault, malloc char pointers -
i keep getting segmentation fault , know char pointer. cant figure out why?
whiskey* createwhiskey(int a, double p, char* n){ whiskey* whiskey = malloc(sizeof(whiskey)); whiskey->age = a; whiskey->proof = p; whiskey->name = malloc((strlen(n)+1) * sizeof(char)); strcpy(whiskey->name, n); return whiskey; } int main(){ whiskey* burbon; burbon = createwhiskey(12, 90.0, "makersmark"); free(burbon); return 0; }
in comment alex (see below) following information added:
typedef struct{ int age; double proof; char* name; }whiskey;
as discussed in comments program shown fine.
however, should add checks avoid problems. like:
typedef struct{ int age; double proof; char* name; } whiskey; whiskey* createwhiskey(int a, double p, char* n){ whiskey* whiskey = malloc(sizeof(whiskey)); if (whiskey) { whiskey->age = a; whiskey->proof = p; if (strlen(n) > some_maximum) { free(whiskey); printf("some error... maybe\n"); return null; } whiskey->name = malloc((strlen(n)+1) * sizeof(char)); if (whiskey->name) { strcpy(whiskey->name, n); } else { free(whiskey); printf("some error... \n"); return null; } } return whiskey; } int main(){ whiskey* burbon; burbon = createwhiskey(12, 90.0, "makersmark"); if (!burbon) { printf("some error... \n"); } // code.... if (burbon) { free( burbon->name); free(burbon); } return 0; }
Comments
Post a Comment