[英]Free array pointed to by a pointer within a struct in C
我有一個在動態數組中實現的堆棧。 以下是我的一些功能。 當我調用stk_reset函數時,似乎沒有完全釋放堆棧。
這是我的結構。 我必須在結構內部有一個指向動態數組的指針
typedef struct stack {
char *items;
int arrSize;
int top;
} StackStruct;
void stack_create(StackStruct *s) {
char *arr = malloc(sizeof(char)*2);
if (arr == NULL) {
printf("Insufficient memory to initialize stack.\n");
return;
}
s->arrSize = 2;
s->items = arr;
s->top = -1;
}
我如何釋放分配堆棧的數組的每個元素? 我將此語句free((s-> items)++)與for循環一起使用,但沒有用。
void stk_reset(StackStruct *s) {
int i;
for (i = 0; i <= s->arrSize; i++)
free((s->items)++);
free(s->items);
s->items = NULL;
s->top = -1;
s->arrSize = 0;
}
您只能在malloc
返回的指針上調用free
,並且只能釋放整個塊,而不是單個字節。
您希望一(1)個調用free
對malloc
每次調用。 在這里,您只分配了一個有兩個字符的空間的項目。 要free
它,這很簡單。 這就是所謂的“安全”發布(或免費)。
if (s->items != NULL) {
free(s->items);
s->items = NULL; // Reset to be safe.
}
盡管要使用它,但是在嘗試使用它之前,需要確保將值初始化為NULL: s->items = NULL;
。
不需要其他free
調用,並且當您只有一個malloc
時,當然不需要循環調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.