I have troubles with memory. I'm using struct this way:
Package.h file
#pragma once
#include <cstdlib>
struct Package {
char *data;
long long int *packageNumber;
long long int *allPackages;
Package(const int sizeOfData);
~Package();
};
Package.cpp
#include "Package.h"
Package::Package(const int sizeOfData) {
void *ptr = malloc(2 * sizeof(long long int) + sizeOfData * sizeof(char));
packageNumber = (long long int*) ptr;
allPackages = (long long int*) ((long long int*)ptr + sizeof(long long int));
data = (char*)((char*)ptr + 2 * sizeof(long long int));
}
Package::~Package() {
free(data);
free(packageNumber);
free(allPackages);
}
And in method:
for (int j = 0; j < this->bufforSize || i * bufforSize + j < allPackages; j++) {
Package package(this->packageSize);
this->file->read(package.data, this->packageSize);
*package.allPackages = allPackages;
*package.packageNumber = i * this->bufforSize + j;
this->dataPacked->push_back(package);
}
after end of brackets it throws error: "HEAP[zad2.exe]: Invalid address specified to RtlValidateHeap( 00000056FEFE0000, 00000056FEFF3B20 )"
I have no idea what I'm doing wrong. Please help, Michael.
EDIT: Now it is working for first iterate of loop. Helps that I changed destructor to this:
Package::~Package() {
free(packageNumber);
}
But now destructor is executed two time on same struct object in 2'nd iterate of loop.
C
when it is obvious that you're using C++. And if this is C++, why not usenew [ ]
anddelete[ ]
or just a container such asstd::vector
? – Oakenfree
3 times? There is only one call tomalloc
being done. – Oakenmalloc
as opposed to usingnew char [ ]
orstd::vector<char>
. They all do basically the same thing, which is allocate a contiguous chunk of memory in bytes. The difference, at least withmalloc
andstd::vector<char>
is that you no longer have to manually manage the allocation and deallocation, which is why you have an error now. – OakenC
way and trying to mix that with C++. If you're going to usestd::vector
to store your objects, then you have to decide whether you want to use standard containers for your data members, or use raw memory and adhere to the "rule of 3", What you want is the latter, but your class fails to implement the rule of 3. – Oaken