holo
holo

Reputation: 331

Segmentation fault (core dumped) with malloc and struct

I can't understand why this simple code doesn't run without causing a segmentation fault on linux :

#include <stdlib.h>

struct entry
{
   int value;
};

void initEntry(struct entry *entry)
{
  entry = malloc(sizeof(struct entry));    
  entry->value = 0;
}

int main()
{
  struct entry *list;

  initEntry(list);    
  list->value = 5;
}

I can run the program after removing the last instruction (list->value = 5;)

I compile with :

gcc main.c -o main

Upvotes: 0

Views: 1728

Answers (1)

Ivan Velichko
Ivan Velichko

Reputation: 6709

You need to change it to:

void initEntry(struct entry **entry) {
  *entry = malloc(sizeof(struct entry));    
  (*entry)->value = 0;
}

int main() {
  struct entry *list;    
  initEntry(&list);    
  list->value = 5;
}

In your code you just lose the address of allocated memory after returning from the initEntry() call. It's because entry argument is a local variable regarding the initEntry() function and assigning of any values to it is invisible from outside. You need an extra inderection level to be able to return the address of the allocated memory.

Upvotes: 6

Related Questions