M
MegapolisPlayer
Guest
MegapolisPlayer Asks: Manipulating memory returns invalid pointer error (C++)
I have a class called
Array has a few member variables:
The class works normally, but when I copy it i get an error, specified below.
Here is the code:
Copy c.:
Destructor:
Test code:
The error I'm getting is munmap_chunk: invalid pointer.
I have tried replacing the for loop with
I have also tried debugging it with gdb, where it always points to either
IO is a wrapper for std::cout with some extra functionality.
I'm using clang(++) 14 on Linux (Mint 21) and the CodeLite 16.4 IDE.
I have a class called
Array
with a copy constructor and a copy assignment operator (which is not important currently).Array has a few member variables:
- mArray is the internal raw array
- mSize is the amount of elements
- mReserved is the amount of currently allocated space
- mMemoryAllocated is a boolean value which determines if any memory has been allocated by the class.
The class works normally, but when I copy it i get an error, specified below.
Here is the code:
Copy c.:
Code:
template<typename tType>
Array<tType>::Array(const Array& aOther) noexcept {
this->mArray = nullptr;
this->mSize = 0;
this->mReserved = 0;
this->mMemoryAllocated = false;
if(aOther.mMemoryAllocated) {
this->mArray = (tType*)malloc(aOther.mReserved * sizeof(tType)); //pointer invalid???
if(this->mArray == nullptr) {
//my custom error handling
}
for(U64 Id = 0; Id < aOther.mSize; Id++) {
this->mArray[Id] = aOther.mArray[Id];
}
this->mSize = aOther.mSize;
this->mReserved = aOther.mReserved;
this->mMemoryAllocated = true;
return;
}
}
Destructor:
Code:
template<typename tType>
Array<tType>::~Array() noexcept {
if(this->mMemoryAllocated) {
//call destructors
for(U64 Id = 0; Id < this->mSize; Id++) {
this->mArray[Id].~tType();
}
free(this->mArray);
}
}
Test code:
Code:
Array<int> TestArray;
TestArray.Add(56);
TestArray.Add(58);
TestArray.Add(66);
TestArray.Add(78);
TestArray.Add(560);
TestArray.Add(690);
TestArray.Add(456);
TestArray.Add(59);
TestArray.Add(57);
TestArray.Add(69);
TestArray.Add(75);
TestArray.Add(555);
TestArray.Add(699);
TestArray.Add(999);
{
Array<int> TestArray2 = TestArray;
TestArray.ShiftRight(3, 2);
TestArray2.ShiftRight(3);
TestArray2.Add(56); //crashes here as well
IO << TestArray << "\n";
IO << TestArray2 << "\n";
} //test array 2 issues
The error I'm getting is munmap_chunk: invalid pointer.
I have tried replacing the for loop with
memcpy
, but to no avail.I have also tried debugging it with gdb, where it always points to either
realloc
or free
calls (confirmed in the call stack)IO is a wrapper for std::cout with some extra functionality.
I'm using clang(++) 14 on Linux (Mint 21) and the CodeLite 16.4 IDE.