Friday 15 January 2010

c - Malloc cannot allocate memory for a structure -



c - Malloc cannot allocate memory for a structure -

i have segmentation fault (core dumped) error.

main.c

#include "header1.h" #include <stdlib.h> #include <stdio.h> int main(int argc, char** argv) { struct t_list *list = null; dofill(list); printf("%s\n", list->name); free(list); homecoming 0; }

header1.h

#ifndef header1_h #define header1_h struct t_list { char *name; struct t_list *next; }; void dofill(struct t_list *list); #endif

worker.c

#include "header1.h" #include <stdlib.h> void dofill(struct t_list *list) { list = (struct t_list *) malloc(sizeof(struct t_list)); char *tmp = "somename"; list->name = tmp; list->next = null; }

when run (gcc -g main.c worker.c -o test) (on line printf in main.c):

segmentation fault (core dumped)

in gdb see:

temporary breakpoint 1, main (argc=1, argv=0x7fffffffddf8) @ main.c:8 8 struct t_list *list = null; (gdb) next 9 dofill(list); (gdb) step dofill (list=0x0) @ worker.c:6 6 list = (struct t_list *) malloc(sizeof(struct t_list)); (gdb) p list $1 = (struct t_list *) 0x0 (gdb) next 7 char *tmp = "somename"; (gdb) p list $2 = (struct t_list *) 0x0

as can see malloc in worker.c doesn't allocate memory list variable (the pointer before , after malloc points @ 0x0).

if move code dofill procedure in main.c works correctly:

main.c

#include "header1.h" #include <stdlib.h> #include <stdio.h> int main(int argc, char** argv) { struct t_list *list; list = (struct t_list *) malloc(sizeof(struct t_list)); char *tmp = "somename"; list->name = tmp; list->next = null; printf("%s\n", list->name); free(list); homecoming 0; } $ gcc -g main.c -o test $ ./test somename

how possible? do wrong?

gcc version 4.8.2 (ubuntu 4.8.2-19ubuntu1)

parameters in c passed copy. changes create list within of dofill() not propagated main(), means list null in main(). seek passing pointer pointer instead:

#include "header1.h" #include <stdlib.h> #include <stdio.h> int main(int argc, char** argv) { struct t_list *list = null; dofill(&list); printf("%s\n", list->name); free(list); homecoming 0; }

and alter dofill() accordingly:

#include "header1.h" #include <stdlib.h> void dofill(struct t_list **list) { *list = malloc(sizeof(**list)); char *tmp = "somename"; (*list)->name = tmp; (*list)->next = null; }

c gcc struct segmentation-fault malloc

No comments:

Post a Comment