Ale*_* Oh 3 c stack-overflow stack heap-memory
我一直在为 LeetCode 上的 Min Stack 编写代码。我遇到的问题是当我尝试重新分配内存(在推送方法上)时,它告诉我“地址清理程序:堆缓冲区溢出”。
这是什么原因造成的,我该如何解决这个问题?谢谢
另外,解决这个问题的更好方法是什么?
typedef struct {
int top;
int *arr;
int min;
int size;
} MinStack;
/** initialize your data structure here. */
MinStack* minStackCreate() {
MinStack* stack = (MinStack*)malloc(sizeof(MinStack));
stack->size = 10;
stack->top = -1;
stack->min = INT_MAX;
stack->arr = (int*) malloc(sizeof(int)*(stack->size));
return stack;
}
void minStackPush(MinStack* obj, int x) {
//if top+1 is equal to the size of the stack(when stack is full),
//I want to multiply the size by 2
//so more numbers can fit in the stack.
if(obj->top+1 == obj->size){
obj->size = obj->size*2; // this line seems to give me issues.
obj->arr = realloc(obj->arr, obj->size);
}
obj->arr[obj->top+1] = x;
obj->top++;
}
Run Code Online (Sandbox Code Playgroud)
这个问题似乎是从你的到来realloc的呼叫,根据手册页:
The realloc() function changes the size of the memory block pointed to by ptr to size bytes。
所以你需要有obj->arr = realloc(obj->arr, sizeof(int) * obj->size);
否则你的索引将被关闭。
似乎您realloc在每次调用时都在调用,而不仅仅是在需要增加数组的大小时,我建议将该调用移到您的if(obj->top+1 == obj->size)语句中。