[英]Malloc and free in loop in C
是否總是需要匹配malloc()和free()調用? 我必須為結構分配動態內存,然后在執行一些操作后將其釋放。 我可以覆蓋動態內存中的數據,還是應該先釋放它們然后再次分配malloc? 舉些例子:
int x =5,len = 100;
do{
struct test *test_p = (struct test *) malloc(sizeof(struct test) + len);
/* ---do some operation ---------- */
free(test_p);
x--;
}while(x);
另一種方法是在循環之前執行malloc,並在循環內部執行free()。 釋放它后可以使用該結構指針嗎? 例如:
int x =5, len = 100;
struct test *test_p = (struct test *) malloc(sizeof(struct test) + len);
do{
/* ---do some operation ---------- */
free(test_p);
x--;
}while(x);
在此先感謝您的幫助和建議。
假設這是使用彈性數組方法並且您的分配有意義,那么您可以在每次迭代期間重用您的內存。 這將為您節省大量的分配和釋放時間。
int x =5,len = 100;
struct test* test_p = malloc(sizeof *test_p + len);
do {
// do some operation using test_p
x--;
} while(x);
free(test_p);
如果要在每次迭代中“清除”結構,則可以在循環開始時使用復合文字來實現。
do {
*test_p = (struct test){0};
當您不再需要某個對象時,始終是一個好習慣。 在您的情況下,如果您在while
循環的每次迭代中使用test
結構,我將編寫如下代碼:
int x =5,len = 100;
struct test *test_p = (struct test *) malloc(sizeof(struct test) + len);
do{
/* ---do some operation ---------- */
x--;
}while(x);
free(test_p);
在您的代碼中:
int x =5, len = 100;
struct test *test_p = (struct test *) malloc(sizeof(struct test) + len);
do{
/* ---do some operation ---------- */
free(test_p);
x--;
}while(x);
調用free(test_p);
,您不應再使用test_p
。 這意味着test_p
僅在第一次循環中有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.