簡體   English   中英

指向C中重新分配的存儲塊的多個指針

[英]Multiple pointers to a reallocated memory block in C

假設我有多個指向堆內存塊的指針。 假設第一個指針是內存的所有者 ,並且在我的應用程序中還有幾個其他的指針充當句柄 只要所有者是唯一可以free的所有者,我們就不會發生內存泄漏,也不會對內存塊加倍釋放。

/* Here is the owner */
size_t block_size = SOME_BLOCK_SIZE;
char *owner = malloc(block_size);

/* And a few handles that access the block in different places */
char *handle_1 = owner[10];
char *handle_2 = owner[359];
char *handle_3 = owner[172];

到現在為止還挺好。 后來我們realloc車主以增加容量

char *tmp = realloc(owner, 2 * SOME_BLOCK_SIZE);
if (!tmp) {
    fprintf(stderr, "Error: could not reallocate array\n");
    exit(-1);
}

if (tmp == owner) {
    printf("We all know what happens here...\n");
    printf("the owner array just increased size\n");
}
else {
    printf("We had to move the owner array to a new memory address\n");
    printf("What happens to the handles?\n");
}

有三種可能的結果:

  1. realloc失敗,因為沒有更多的內存。
  2. realloc成功擴展了數組,而無需移動它。
  3. realloc成功擴展了數組,但是將其移至新的內存區域。

我的問題是,在情況3中,我們之前定義的句柄會發生什么? 我希望由於它們只是指針變量,並且由於realloc函數不知道它們的存在,因此句柄仍指向舊的內存地址。 很難想象情況會變得很糟。

我的直覺正確嗎? 如果是這樣,解決此問題的最佳方法是什么(除了永不調整大小)? 恐怕我將不得不保留一個活動手柄的列表,並在檢測到owner被移動時對其進行更新。 我對如何實現這個想法有一個想法,但是我寧願使用別人的聰明解決方案,也不願重新發明輪子。

是的,像ryan和true建議一樣,您應該使用基本指針(所有者)。 在重新分配的情況下,可以更新此基本指針。 您的句柄應作為此基本指針的偏移量進行管理。

int handle1_off = 10;
int handle2_off = 359;
...

如果要訪問句柄,則必須計算實際指針。

memcpy(owner + handle1_off, some_other_pointer, some_size);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM