【问题标题】:Proper way to have two pointers point to the same memory chunk让两个指针指向同一个内存块的正确方法
【发布时间】:2015-06-28 19:21:23
【问题描述】:

我有一个结构:

struct generic_attribute{
    int current_value;
    int previous_value;
};

还有一个构造函数,它输出指向这个结构的指针:

struct generic_attribute* construct_generic_attribute(int current_value){
    struct generic_attribute *ga_ptr;
    ga_ptr = malloc (sizeof (struct generic_attribute));
    ga_ptr->current_value = current_value;
    ga_ptr->previous_value = 0;
    return ga_ptr;
}

现在,在另一个函数中,我想定义一个指针并将其设置为指向与上述构造函数输出的指针相同的地址。

struct tagged_attribute* construct_tagged_attribute(int num_args, int *args){
    ...
    struct generic_attribute* generic = malloc (sizeof(struct generic_attribute));
    generic = construct_generic_attribute(args[0]);
    ...
}

在我看来,我在这里所做的是:

1) 我定义了一个“通用”指针并分配一个内存块来保存 generic_attribute 结构的实例。

2) 我调用一个函数construct_generic_attribute,在该函数中,程序再次分配一个generic_attribute 结构大小的内存块。它输出一个指向这个内存块的指针。

3) 在construct_tagged_attribute中,我设置“generic”指针等于construct_generic_attribute函数输出的指针,所以现在它们都指向同一个内存槽。

但是,我分配的内存似乎是我需要分配的两倍。

有没有办法让我只分配一次内存而不会因为未能为“通用”指针分配空间而出现分段错误?或者,我是否误解了这段代码中发生的事情?

【问题讨论】:

    标签: c pointers memory memory-management allocation


    【解决方案1】:
    struct generic_attribute* generic = construct_generic_attribute(args[0]);
    

    应该做的伎俩。指针变量就是这样,一个变量。您可以像数字一样交换指针值。

    【讨论】:

      【解决方案2】:
      1. 是的,你误会了,但我无法完全弄清楚你认为发生了什么来解释它是怎么错的。

      2. struct generic_attribute *generic = construct_generic_attribute(args[0]); 指针是一种值。如果您将一个指针分配给另一个,您将获得两个指向同一事物的指针,而无需分配任何内存。由于 C 不会为您管理内存,因此您需要确保分配的任何对象都只释放一次,并且在对象被释放后不要尝试使用指向该对象的指针。

      【讨论】:

        【解决方案3】:

        这里

            struct generic_attribute* generic = malloc (sizeof(struct generic_attribute));
        

        你分配了一个足够大的内存块来保存generic_attribute 结构,然后在generic 变量中存储指向该结构的指针(技术上:块的地址)。 注意:您不初始化结构成员。

        然后在

            generic = construct_generic_attribute(args[0]);
        

        您调用一个函数,该函数在内部分配(另一个)内存块并对其进行初始化并返回一个指向它的指针(该指针在函数执行期间存储在ga_ptr 变量中)。然后将返回的指针分配给generic 变量,覆盖由前一条指令存储在那里的值。因此,您失去了对第一个分配结构的访问权限。

        编辑

        恐怕我不太明白您想要达到的目标。如果你想要两个指向同一个结构的指针,只需声明ga1 并为其分配一个指向已创建结构的指针:

            struct generic_attribute *ga1 = construct_generic_attribute(args[0]);
        

        然后复制指针:

            struct generic_attribute *ga2 = ga1;
        

        【讨论】:

          猜你喜欢
          • 2014-08-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-10-17
          • 1970-01-01
          • 2021-11-10
          • 1970-01-01
          相关资源
          最近更新 更多