2016-11-24 63 views
-1

所以我想優化我的記憶在我的代碼管理。Malloc和免費的功能(優化你的記憶)

下面的代碼的示例:

Image image; 

    int main(int argc, char *argv[]) 
    { 

    image = (Image) malloc(sizeof (struct image)); 

    image = doSomething(image); 


    } 

    Image doSomething(Image imageInput) { 
    Image imageResult; 

    imageResult = (Image) malloc(sizeof (struct image)); 

    //Code does something here 

    return imageResult; 

    } 

當它是適當的使用免費的();在我的例子?

Image image; 

int main(int argc, char *argv[]) 
{ 

image = (Image) malloc(sizeof (struct image)); 

image = doSomething(image); 


free(image); 
} 

Image doSomething(Image imageInput) { 
Image imageResult; 

imageResult = (Image) malloc(sizeof (struct image)); 

//Code does something here 

free(imageInput); 
return imageResult; 

} 

唯一一次我可以看到是supossed在功能被複制和被假設函數結束之後要被擦除的「imageInput」變量。

釋放函數變量是矯枉過正嗎?

也在應用程序執行結束時。

+0

*您不能*'free'函數變量:您可以將其與功能的'malloc'家庭只分配'free'內存。無論如何,當你退出函數時,函數變量的生命結束。 –

+1

[請參閱此討論,爲什麼不在'C'中爲malloc()'和family生成返回值。](http://stackoverflow.com/q/605845/2173917)。 –

+1

通過(大概)定義一個指向圖像類型的指針,你不清楚你正在分配什麼,以及有多少。 'image =(image)malloc(sizeof(struct image));''''''''因爲您已經使用了'image' *和*'struct image',所以''看起來很吝嗇,並且您是否只爲'pointer'分配足夠的內存還不清楚。定義指針類型的做法很糟糕。 –

回答

0

你必須制定有關使用你的圖像處理功能的習慣。我不認爲你的榜樣是壞的。但我認爲你可以做得更好。

這是唯一的例子,但我認爲你可以做這樣的事情:

struct image *img_alloc() 
{ 
    return malloc(sizeof(struct image)); 
} 

void img_free(struct image **a) 
{ 
    free(*a); 
    *a = NULL; 
} 

struct image **img_add(struct image **dstp, struct image const *lhs, struct image const *rhs) 
{ 
    struct image *dst = img_alloc(); 
    ... 
    img_free(dstp); 
    *dstp = dst; 
    return dstp; 
} 

int main(int argc, char *argv[]) 
{ 
    struct image *img = NULL; 
    ... 
    img_add(&img, a, b); 
    ... 
    img_add(&img, img, c); 
    ... 
    img_add(&img, *img_add(&img, img, a), b); 
    ... 
    img_free(&img); 

    return 0; 
} 
0

最後我用的valgrind分析任何內存泄漏。

非常有幫助指導某人進入這項任務。幫助我學習何時做一個免費()和在哪裏。

這裏是一個有用的鏈接: Valgrind website