I've got a simple program that stores sets of 3 variables using two classes, one called Stock
which has the 3 variable definitions, along with basic inspector and mutator functions, and a second function called StockManagement
that has a pointer to Stock
and some other functions that do all sorts of things such as creating a dynamic array of Stock
, dumping a files data into the array we just made and so on and so forth.
Everything works fine in terms of creating the stuff (such as the constructor, array, entering data, reading data) but when it comes to the destructor, there is a chance that SOMETIMES the program will seg fault at the delete command, and the times it doesn't, the data is still accessable for some reason or another.
Here's what I believe to be the important parts of the code
Header file
class Stock {
private:
char tag[5];
int cost;
long volume;
public:
void setTag(char);
void setCost(int);
void setVolume(long);
char* getTag();
int getCost();
long getVolume();
}
class StockManagement {
private:
Stock* data;
int size;
public:
StockManagement();
~StockManagement();
// other functions
}
Cpp file (the proper name escapes me)
...
void Stock::setTag(char tag) {
this->tag = tag;
}
void Stock::setCost(int cost) {
this->cost = cost;
}
void Stock::setVolume(long volume) {
this->volume = volume;
}
char* Stock::getTag() {
return this->tag;
}
int Stock::getCost() {
return this->cost;
}
long Stock::getVolume() {
return this->volume;
}
// --
StockManagement::StockManagement() {
data = NULL;
size = 0;
}
StockManagement::~StockManagement() {
if (data != NULL) {
std::cout << data[0].getTag() << std::endl; // Debug line
delete [] data;
std::cout << data[0].getTag() << std::endl; // Debug line
data = NULL;
size = 0;
}
}
void StockManagement::allocateMemory() {
data = new Stock[size];
}
...
So at the point in time when calling the destructor, there is always data in there. Theres a function always called that gets the amount of lines from a file (and saves it as size
) which is used to allocate the memory, in which data is then entered into the array.
Then comes time to use the destructor. The first cout line will always output, as expected. Then theres a chance that either two things happen from then on. We seg fault at the delete line, or we go over it, calling the second cout and somehow printing the same data we printed the first time.
So obviously the data wasn't deleted. But why? And why does this only happen sometimes and other times it just straight up seg faults?