Malloc on a Pointer Parameter Failing

允我心安 提交于 2019-12-08 07:26:06

问题


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.


回答1:


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;
}



回答2:


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);


来源:https://stackoverflow.com/questions/10369838/malloc-on-a-pointer-parameter-failing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!