2010-11-27 119 views
0

我在我的項目中創建一個結構並返回指針的c函數。c內存泄漏問題

typedef struct object 
{ 
float var1; 
float var2; 
} 
Object; 

Object *createObject(float newVar1, float newVar2) 
{ 
Object *object; //create new structure 
object = (Object*)malloc(sizeof(Object)); //malloc size for struct object 
if(object != NULL) //is memory is malloc'd 
{ 
    object->var1 = newVar1; //set the data for var1 
    object->var2 = newVar2; //set the data for var2 
    return object; //return the pointer to the struct 
} 
return NULL; //if malloc fails, return NULL 
} 

現在的結構被使用過了一陣,我想刪除這個結構之後,我做了這個功能:

void deleteMarnix(Object *objectPointer) 
{ 
free(objectPointer); //free the memory the pointer is pointing to 
objectPointer = NULL; //stop it from becomming a dangling pointer 
} 

這最後的代碼段展示瞭如何使一個對象,使用它,並嘗試刪除它,但是,它似乎並沒有完全釋放內存。我究竟做錯了什麼?

Object *object = createObject(21.0f, 1.87f); 
//do things here with object. 
deleteMarnix(object); 
+0

你需要顯示你如何知道它泄漏,你可能會看到CRT預先分配。 – Puppy 2010-11-27 13:02:37

+0

你是什麼意思,「它似乎並沒有完全釋放內存」? – 2010-11-28 12:34:05

回答

2

free()所做的並不是完全釋放指針所佔用的內存,但實際上,如果在調用free()後調用malloc,它實際上可供以後使用。

一個證據是,你將能夠在空閒調用並將指針設置爲NULL之前訪問內存位置(假設你還沒有調用malloc())。當然,這些值將重置爲某些默認值。 (在我發現int的一些編譯器被設置爲0)。

雖然沒有內存泄漏,這可能會回答你的問題。

讓我們知道:)

3

從您發佈的片段中,沒有泄漏。

我認爲,隨着:

它似乎沒有完全釋放內存

你的意思是object仍持有舊值。


deleteMarnix,當你設置objectPointerNULL,你只設置在功能範圍指針的值。

它不會在外部函數中設置實際指針object的值。

要做到這一點,你可以:

  1. 它設置爲NULL外功能

    Object *object = createObject(21.0f, 1.87f); 
    deleteMarnix(object); 
    object = NULL; 
    
  2. 指針的指針傳遞給deleteMarnix功能:

    void deleteMarnix(Object **objectPointer) 
    { 
        free(*objectPointer); //free the memory the pointer is pointing to 
        *objectPointer = NULL; //stop it from becomming a dangling pointer 
    } 
    ... 
    Object *object = createObject(21.0f, 1.87f); 
    deleteMarnix(&object); 
    
+0

它應該仍然被釋放()並且不會泄漏。 – Puppy 2010-11-27 13:02:18