的malloc一个指针参数失败问题 [英] Malloc on a Pointer Parameter Failing

查看:156
本文介绍了的malloc一个指针参数失败问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有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

下面是c_obj_initalizer的定义是:

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

为什么在c_obj_initalizer方法的malloc不能保持连接到当该方法返回一个参数传递的指针?这似乎是调用initalizer没有做任何事情。我认识到,通过实际c_obj_thing不作为指针将意味着在initalizer所做的更改未归,但我认为在整个程序中动态内存延续。

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.

推荐答案

因为当你把它发送指针的副本的功能,当你在函数改变它,你不调用方法改变。您需要初始化之前对malloc它。

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.

例如:

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

这篇关于的malloc一个指针参数失败问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆