Monday, April 30, 2012

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.





No comments:

Post a Comment