【发布时间】:2021-03-02 01:32:27
【问题描述】:
我有一个程序,它创建一个名为 Stack 的结构,该结构包含一个指向 int 数组的指针和一个显示该数组大小的 int。 我有以下功能:
- 用空值初始化结构
- 将整数推入数组(动态分配更多内存并向其写入值)
- 从数组中弹出一个 int
但是,当我尝试通过释放它占用的内存来弹出最后一个元素时,我的程序崩溃了。
我在这里做错了什么?
我的流程正确吗?
我意识到问题可能是我试图释放一段尚未动态分配的内存,但我只是不知道问题出在哪里。
#include <stdio.h>
#include <stdlib.h>
#include <mem.h>
struct Stack{
int *array;
int size;
};
typedef struct Stack Stack;
void initStack(Stack *stack);
void push(Stack *stack, int value);
int pop(Stack *stack);
int main()
{
Stack firstStack;
initStack(&firstStack);
push(&firstStack, 1222);
pop(&firstStack);
push(&firstStack, 555);
for(int i = 0; i < firstStack.size; ++i){
printf("#%d: %d (%p) ", i , firstStack.array[i], &firstStack.array[i]);
}
return 0;
}
void initStack(Stack *stack){
stack->array = NULL;
stack->size = 0;
}
void push(Stack *stack, int value){
int size = stack->size;
int newSize = size + 1;
stack->array = realloc(stack->array, newSize * sizeof(int));
if(stack->array != NULL){
stack->array[size] = value;
stack->size = stack->size + 1;
}
else{
printf("MALLOC ERROR");
}
}
int pop(Stack *stack){
int lastValue = stack->array[stack->size];
int lastIndex = (stack->size)-1;
int* lastAddress = (stack->array)+lastIndex;
free(lastAddress);
stack->size = (stack->size) - 1 ;
printf("memory free\n");
return lastValue;
}
【问题讨论】:
-
你应该总是使用一个新的指针变量来收集
realloc的返回地址,假设你的第三个push失败了,stack->array的值是多少
标签: arrays c struct free realloc