my project is a dynamic array wrapper like std::vector. this is how it works:
when adding a new element, the memory is either allocated (malloc), if it is 0, or reallocated with a new size (realloc), if it is not 0. the size is the number of elements * size of type
when getting an already added element, i calculate the address by multiplying its index by the size of the type and adding it to the address at which the memory is allocated
NOTE: i write and read the memory myself with no function like memcpy or memset. this is required for my project. it should be possible for me to do this so if you could, do not mention it (unless i implemented it wrong, in which case, please do mention it)
when i try to read in an added element with the get(int index)
function, i either get a "stack around variable was corrupted" or "read access violation" error, depending on how I try to do it.
i read a bit online and found i may have corrupted the heap somehow with malloc. also read i could find out where the error is with something called "valgrind", but it seems to only be available for linux, and i use windows.
here is my code (its rewritten, all error checks were removed to make it smaller). the place where i get the error is commented:
template<class T>
class darr
{
public:
darr(void) {}
~darr(void) {
erase(); dealloc();
}
bool alloc(int elemc) {
this->elemc = elemc;
this->size = (elemc * sizeof(T));
this->end = (this->start + this->size);
if (this->start)
{
this->start = (T*)(realloc(this->start, this->size));
if (this->start)
{
this->end = (this->start + this->size);
return true;
}
}
else
{
this->start = (T*)(malloc(this->size));
if (this->start)
{
this->end = (this->start + this->size);
return true;
}
}
return false;
}
bool erase(void)
{
for (int i = 0; i <= this->size; ++i)
{
*(unsigned long*)(this->start + i) = 0;
}
return true;
}
bool dealloc(void)
{
free(this->start);
return true;
}
bool add(T obj)
{
void* end_temp = 0;
if (this->end) { end_temp = this->end; }
if (true == this->alloc(++this->elemc))
{
end_temp = this->end;
for (int i = 0; i <= sizeof(obj); ++i)
{
*(unsigned long*)((unsigned long)(end_temp)+i) = *(unsigned long*)((unsigned long)(&obj) + i);
}
}
return true;
}
T get(int i)
{
unsigned long siz = sizeof(T);
void* i_addr = this->start + (i * siz);
//T tempobj = 0;
T* tempobj = (T*)(malloc(sizeof(T)));
// without malloc - stack around var corrupted (happnens at last index in for loop, no matter what index it is)
// with malloc - read access violation
for (int i = 0; i <= siz; ++i)
{
*(unsigned long*)((unsigned long)(&tempobj)+i) = *(unsigned long*)((unsigned long)(i_addr)+i);
}
return *tempobj;
}
private:
T * start;
void* end;
int elemc, size;
};