[英]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.