I'm trying to implement a dynamic array and here is my function for increasing the capacity
int* changeCapacity(int *arr, int length, int newCapacity) {
int *newArr = new int[newCapacity];
if(length > newCapacity){
return 0;
} else {
for(int i = 0; i < length; i++){
newArr[i] = arr[i];
}
delete[] arr;
arr = newArr;
return arr;
}
}
This is the error i get:
speicher(2465,0x7fff7cfc2310) malloc: * error for object 0x7f9742403910: pointer being freed was not allocated * set a breakpoint in malloc_error_break to debug
i'm calling it like this:
int* addElement(int *arr, int& length, int& capacity, int val){
if(length >= capacity){
capacity = capacity * 2;
changeCapacity(arr, length, capacity);
arr[length] = val;
length += 1;
return arr;
}else{
arr[length] = val;
length += 1;
return arr;
}
}
Right now you are changing the address of
arr
, in which you have to pass the pointer by reference. Do this:This is somewhat a guess based on the error message, but you have shown:
which calls:
However, the original source of the
arr
argument toaddElement()
is unknown given the code you have posted so far. Are you by chance doing something like this:or maybe calling
addElement()
with a global array variable? In either of those cases, the original array is not allocated via anew[]
to match thedelete[]
, and this would appear to be what the runtime library is complaining about. The value of the pointer stated in the error message tends to make me think it was allocated on the stack initially.Of course the other issues, like not capturing the return value of
changeCapacity()
and/oraddElement()
, and the possibility thatchangeCapacity()
might return a NULL pointer are still valid as well, and should be fixed.Here is a better way of doing it. Everything is well explained in the comments for anyone who wants to learn:
I assume that your problem must come from two things IMO :
First:
Here you doesn't get the new arr value (returned by changeCapacity()). So your function addElement() will return Wrong pointer and on your next addElement() that will do free memory corruption.
Why do you have to get the new arr value?
You do the same as here
How will be the value of a? 1 because the argument of changeVar is a local variable.
Second:
You give a NULL value on your addElement() function.