[英]Proper way to have two pointers point to the same memory chunk
我有一个结构:
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”,并分配了一个内存块来保存generic_attribute结构的实例。
2)我调用一个函数construct_generic_attribute,在该函数中,程序再次分配一个大小为generic_attribute结构的内存块 。 它输出一个指向该内存块的指针。
3)在construct_tagged_attribute中,我将“通用”指针设置为与construct_generic_attribute函数输出的指针相等,因此现在它们都指向相同的内存插槽。
但是,看来我分配的内存是我需要分配的两倍。
有没有一种方法可以让我只分配一次内存,而不会因无法为“通用”指针分配空间而导致分段错误? 另外,我是否误解了这段代码中发生了什么?
struct generic_attribute* generic = construct_generic_attribute(args[0]);
应该做到的。 指针变量就是那个变量。 您可以像围绕数字一样交易指针值。
是的,您误会了,但是我无法完全弄清您的想法以解释它是怎么回事。
struct generic_attribute *generic = construct_generic_attribute(args[0]);
指针是一种价值。 如果将指针分配给另一个指针,则将获得指向同一对象的两个指针,而不分配任何内存。 由于C不会为您管理内存,因此您有责任确保所分配的任何对象都完全释放一次,并且不要在释放对象后尝试使用指向该对象的指针。
这里
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.