[英]C - How to use free() to free a struct in memory?
我需要一些幫助來為結構分配內存。
我在變量中存儲了指向內存位置的指針,但是我想在使用后重新分配內存。 但是,當我嘗試重新分配內存時,它僅重新分配了第一個結構項( name
),並且age
保留在內存中。 我的代碼可以在下面看到。
int main(int argc, char **argv)
{
struct employee {
char *name;
int age;
};
// Make pointer, employee struct and put struct in memory at pointer location
struct employee *employee_1;
struct employee new_employee;
new_employee.name = "Sue";
new_employee.age = 26;
employee_1 = (struct employee *) malloc(sizeof(new_employee));
(*employee_1).name = new_employee.name;
(*employee_1).age = new_employee.age;
// ... Some operations done
// Deallocate memory location
free(employee_1);
return 0;
}
員工的姓名和年齡肯定都存儲在內存位置,但是我不能同時分配它們。 我測試了它在結構中有兩個以上的項目,並且每次它都是僅第一個被釋放的項目。
我嘗試了幾種不同的方法,例如,分別釋放每個方法,以免出現問題free((*employee_1).name)
但這會引發錯誤。 任何幫助,將不勝感激。
不,您不會自行分配 age
。 那不是“由malloc()
和family返回的指針”,因此您不需要對此(調用) free()
。
引用C11
,第§7.22.3.3章( 重點是我的 )
free
函數使ptr
指向的空間被釋放,即可以用於進一步分配。 如果ptr
是空指針,則不執行任何操作。 否則, 如果參數與內存管理函數先前返回的指針不匹配,或者如果通過調用free
或realloc
釋放了空間,則該行為是不確定的。
此外,FWIW, free()
需要一個指針,因此即使傳遞age
成員變量的地址也將是錯誤的。 一旦程序終止,分配的內存將由OS或內存管理器自動重新分配。
綜上所述,您僅應使用由內存管理函數(即malloc()
和family)返回的指針調用free()
。 其他指針(即使它們是指針)即使沒有通過內存管理功能分配的內存(即snot是否存儲malloc()
和family返回的指針)也不必是free()
d。
例如,在您的情況下,不要在(*employee_1).name
上調用free()
(而是使用employee_1->name
,以提供更好的可讀性,恕我直言),因為內存管理函數不會返回該指針。 這樣做將引起未定義的行為 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.