簡體   English   中英

兩個指針指向同一個內存地址,如何避免在獨立位置發生這兩個釋放的情況下的內存泄漏?

[英]Two pointers are pointing to same memory address, how to avoid memory leak in case freeing of these two happens at independence place?

int *a = malloc(40);
int *b;
b=a;
if( *some conditions* )
free(a);
// I know that 'a' has been allocated this chunk of memory X times
// and free(a) has been called less than X times.

我不知道這種情況,所以不知道“ a”是否已釋放! 因此,現在我將如何確定是否釋放了“ b”即“ a”。

如果要確保對動態分配的內存的指針的后續free調用不會造成任何損害,則應為該指針分配NULL 因為(添加了重點):

free()函數釋放ptr指向的內存空間,該內存空間必須已由先前對malloc(),calloc()或realloc()的調用返回。 否則,或者如果之前已經調用過free(ptr),則會發生未定義的行為。 如果ptr為NULL,則不執行任何操作。

如果你想確保指針b將永遠指向同一個對象的其他指針a點,你可以把b成一個指向a來代替(解引用它每次你需要使用它的時間):

#include <stdio.h>
#include <stdlib.h>

int main() {
    /* dynamically allocate some memory */
    int *a = malloc(40);
    /* b is a pointer to a pointer to an int */
    int **b;
    /* make b point to a */
    b = &a;
    if ( 1 ) {
        /* free memory and assign NULL to the pointer */
        free(a);
        a = NULL;
    }
    /* nothing bad will happen when we dereference b now */
    printf("%p\n", *b);
    /* nothing bad will happen when we free the memory region
       where the pointer b points to points to */
    free(*b);
}

內存泄漏的另一件事。 雙重釋放內存時,不會有內存泄漏。 在這種情況下,您會陷入不確定的行為,在這種情況下可能會發生任何事情 僅僅因為您將不訪問不是您自己的內存區域(不再) (參見此好帖子) 相反,當您丟失對動態分配的內存塊的引用時,您將泄漏內存。 例如:

/* allocate some memory */
int *a = malloc(40);
/* reassign a without free-ing the memory before : you now have leaked memory */
a = malloc(40);

最好的選擇是沒有兩個指向同一位置的指針被獨立釋放。
但是,如果這確實是您所需要的,那么您需要一個參考計數。

以下代碼實現了一個非常簡單的引用計數機制。
當為數據分配第二個指針時,應使用clone_x增加引用計數。
每次釋放時,請使用free_x ,它將釋放一次。

請注意,此代碼不是多線程安全的。 如果您的代碼是多線程的,則需要原子操作,並且在使用它們時需要非常小心。

struct x {
    int refcount;
    int payload;
};
struct x *create_x(int payload) {
    struct x *newx = malloc(sizeof(*newx));
    if (!newx) return NULL;
    newx->payload = payload;
    newx->refcount = 1;
    return newx;
}
void clone_x(struct x *myx) {
    myx->refcount++;
}
void free_x(struct x *oldx) {
    oldx->refcount--;
    if (oldx->refcount == 0) {
         free(oldx);
    }
}

你不能 調用free(a) ,訪問該內存不再安全。

即使你malloc()新的內存和分配結果a ,內存可以在任何地方。

您嘗試執行的操作無效。

每個分配的內存塊都應有一個“所有者”,a或b,如果a是所有者,則指針b不應釋放該塊,反之亦然。

暫無
暫無

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

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