I am new to c++. From what I know, everytime I use "new", I need to delete the allocated memory using "delete". My problem is that I've written some code, but I can't figure out how to deallocate the memory in it.
I have these two functions:
double *Layer::calculateOutputs(const double *inputs) {
auto *weightedInputs = new double[numCurrentLayerNodes];
//function fills up the array here
return weightedInputs;
}
double *NeuralNetwork::calculateOutputs(double *inputs) {
for (auto &layer: layers) {
double *layerOutput = layer.calculateOutputs(inputs);
delete[] inputs;
inputs = layerOutput;
}
return inputs;
}
The way it is right now I get a heap corruption error, but I don't really understand why. If I don't delete inputs and I change the function to something like this:
double *NeuralNetwork::calculateOutputs(double *inputs) {
for (auto &layer: layers) {
inputs = layer.calculateOutputs(inputs);
}
return inputs;
}
The error disappears, but I'm pretty sure that even though I changed what array "inputs" points to, those arrays are still somewhere in memory, so where exactly am I supposed to delete it?
I know I could save myself a lot of pain by just using vectors, but this isn't my first programming language, so I kind of want to challenge myself and try to manage memory and stuff, since that is what I find interesting about c++ in the first place.