我用 C 实现了一个堆栈及其函数。现在调用所有函数后,我想释放堆栈。
我的问题是我应该先释放堆栈“st”的基指针还是直接释放堆栈“st”?两者似乎都适用于我的代码。
#include <stdio.h>
#include <stdlib.h>
#define init_size 10
#define increment 1
typedef struct sqStack
{
int* top;
int* base;
int stack_size;
}sqStack;
int init_stack(sqStack* sq)
{
if(sq->base==NULL)
{
sq->base = (int*)malloc(init_size*sizeof(int));
}
if(sq->base==NULL) exit(-1);
sq->stack_size=init_size;
sq->top=sq->base;
return 1;
}
int push(sqStack* sq, int e)
{
if(sq==NULL) exit(-1);
if(sq->top-sq->base==sq->stack_size-1)//pointer top reaches the top of the stack
{
int* q = (int*)realloc(sq->base,(sq->stack_size+increment)*sizeof(int));
if(q==NULL) exit(-1);
sq->base=q;
sq->top=sq->base+sq->stack_size-1;
sq->stack_size += increment;
}
*sq->top++=e;
return 1;
}
int pop(sqStack* sq,int* e)
{
if(sq==NULL) exit(-1);
if(sq->base==sq->top) exit(-1);
sq->top--;
*e=*sq->top;
sq->stack_size--;
return *e;
}
int top(sqStack* sq,int* e)
{
if(sq==NULL) exit(-1);
if(sq->base==sq->top) exit(-1);
*e=*(sq->top-1);
return *e;
}
int empty(sqStack* sq)
{
if(sq->base==sq->top) return 1;
else return 0;
}
int main() {
sqStack* st= (sqStack*)calloc(1,sizeof(sqStack)) ;
int e;
init_stack(st);
for(int i=0;i<12;i++)
{
push(st,i+1);
}
for(int i=0;i<12;i++)
{
printf("%d\n",top(st,&e));
printf("%d\n",pop(st,&e));
}
free(st->base);
free(st);
return 0;
}
结果是: 12 12 11 11 10 10 9 9 8 8 7 7 6 6 5 5 4 4 3 3 2 2 1 1 每个数字位于一行。
最佳答案
就 malloc
和 free
而言,您拥有的内容是正确的。
您应该只传递从 malloc
或 realloc
返回的内容到 free
。您为结构体和堆栈分配空间,然后释放两者,因此不会泄漏任何内存。
您不想首先free(st)
,因为这样做之后st
指向的内存不再有效,并且您随后不能安全地释放(st->base)
。此外,由于 free
对给定内存的内容一无所知,因此它不会尝试释放该内存可能包含的任何指针。因此,仅调用 free(st)
就会泄漏 st->base
中的内存。
关于c - 释放用 C 实现的堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54672712/