Tanaki
Tanaki

Reputation: 2635

Malloc on a Pointer Parameter Failing

I have the following lines of code:

struct c_obj_thing *object = NULL;
c_obj_initalizer(object);
// at this point, (object == NULL) is 'true'
printf("Value: %d\n", object->value); // this segfaults

Here is the definition for c_obj_initalizer:

int c_obj_initalizer(struct c_obj_thing *objParam) {
  objParam = malloc(sizeof(struct c_obj_thing));
  objParam->pointerThing = NULL;
  objParam->value = 0;
  return 0;
}

Why does the malloc in the c_obj_initalizer method not stay attached to the pointer passed as a parameter when the method returns? It seems like the call to the initalizer doesn't do anything. I realize that passing an actual c_obj_thing not as a pointer would mean that the changes made in the initalizer did not return, but I thought that dynamic memory perpetuated throughout the entire program.

Upvotes: 1

Views: 1474

Answers (2)

Ondrej Peterka
Ondrej Peterka

Reputation: 3427

If you need for some reason do the allocation in the function c_obj_initalizer, you have to pass pointer to pointer to that function:

int c_obj_initalizer(struct c_obj_thing ** objParam) {
  *objParam = malloc(sizeof(struct c_obj_thing));
  *objParam->pointerThing = NULL;
  *objParam->value = 0;
  return 0;
}

and than call like this:

struct c_obj_thing *object = NULL;
c_obj_initalizer(&object);

Upvotes: 2

drew212
drew212

Reputation: 506

Because when you call a function it is sending a copy of the pointer, when you change it in the function you don't change in the calling method. You need to malloc it before initializer.

For example:

struct c_obj_thing *object = malloc(sizeof(struct c_obj_thing));
c_obj_initalizer(object);
printf("Value: %d\n", object->value); // this segfaults


int c_obj_initalizer(struct c_obj_thing *objParam) {  
  objParam->pointerThing = NULL;
  objParam->value = 0;
  return 0;
}

Upvotes: 4

Related Questions