堆缓冲区溢出试图重新分配内存。 C语言

Heap Buffer Overflow trying to reallocate memory. C Language

我一直在为 LeetCode 上的 Min Stack 编写代码。 我遇到的问题是当我尝试重新分配内存(使用推送方法)时,它告诉我 "Address Sanitizer: Heap Buffer Overflow."

这是什么原因造成的,我该如何解决这个问题?谢谢

此外,解决这个问题的更好方法是什么?

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++;
}

Insufficient/incorrect分配。 realloc() 需要字节数,而不仅仅是元素数。

// obj->arr = realloc(obj->arr, obj->size);
obj->arr = realloc(obj->arr, sizeof *(obj->arr) * obj->size);

旁白:健壮的代码会在分配给 obj->arr 之前检查 realloc() 结果。

根据手册页,问题似乎来自您的 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,而不是仅在需要增加数组大小时调用,我建议将该调用移到 [=14= 内部]声明。