Reputation: 91
I've been writing codes for Min Stack on LeetCode. Problem I'm having is when I try to reallocate memory(on push method), it tells me "Address Sanitizer: Heap Buffer Overflow."
What's causing this and how can I fix the issue? Thank you
Also, what would be a better way to solve this problem?
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++;
}
Upvotes: 3
Views: 392
Reputation: 154305
Insufficient/incorrect allocation. realloc()
needs the byte count, not just the element count.
// obj->arr = realloc(obj->arr, obj->size);
obj->arr = realloc(obj->arr, sizeof *(obj->arr) * obj->size);
Aside: Robust code would check the realloc()
result before assigning to obj->arr
. @Eugene Sh.
Upvotes: 3
Reputation: 631
The problem seems to be coming from your realloc
call, according to the man page:
The realloc() function changes the size of the memory block pointed to by ptr to size bytes
.
So you need to have obj->arr = realloc(obj->arr, sizeof(int) * obj->size);
Otherwise your indexing will be off.
It also seems that you're calling realloc
on every call, rather than only when you need to increase the size of your array, I'd advise moving that call to inside your if(obj->top+1 == obj->size)
statement.
Upvotes: 5