I have the 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);
return 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 I run this (gcc -g main.c worker.c -o test
) I get (on the line with printf
in main.c):
Segmentation fault (core dumped)
In gdb
I see:
Temporary breakpoint 1, main (argc=1, argv=0x7fffffffddf8) at main.c:8
8 struct t_list *list = NULL;
(gdb) next
9 doFill(list);
(gdb) step
doFill (list=0x0) at 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 you can see malloc
in worker.c doesn't allocate memory for the list
variable (the pointer before and after malloc
points at 0x0
).
If I move the code from the doFill
procedure in main.c it 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);
return 0;
}
$ gcc -g main.c -o test
$ ./test
somename
How is it possible? What do I do wrong?
gcc version 4.8.2 (Ubuntu 4.8.2-19ubuntu1)