我很困惑为什么删除[](以及删除以及此类问题)失败,当我尝试在指向新指针的指针上调用它时
// Start with output first
float* sigmas = new float[_M];
float* sigmasNext = new float[_M];
for (int i = 0; i < _M; i++) // Loop through and attempt to learn the outputs
{
sigmas[i] = _output[i].Learn(inputValues, outputValues[i]); // Learn
}
// Then the hidden layers
float* weights;
// The first layer
for (int j = 0; j < _H[0]; j++)
{
weights = new float[_M];
for (int k = 0; k < _M; k++)
{
weights[k] = _output[k].GetWeights()[j];
}
sigmasNext[j] = _hidden[0][j].Learn(inputValues, sigmas, weights, _M);
delete [] weights;
}
delete [] sigmas;
// The other hidden layers
for (int i = 1; i < _Hcount; i++)
{
sigmas = sigmasNext;
sigmasNext = new float[_H[i - 1]];
for (int j = 0; j < _H[i]; j++)
{
weights = new float[_H[i - 1]];
for (int k = 0; k < _H[i - 1]; k++)
{
weights[k] = _hidden[i - 1][k].GetWeights()[j];
}
sigmasNext[j] = _hidden[i][j].Learn(inputValues, sigmas, weights, _H[i - 1]);
delete [] weights;
}
delete [] sigmas;
}
了解():
float sigma;
// Get the output of this neuron
float net = Net(inputs);
float out = FireOnNet(net);
float derive = DerivedValue(net);
// Learning
// Sigma(hidden)[i] = sum(sigma[k] * w[k]; 1 -> K) * f'(net)
// deltaW[i] = alpha * sigma * net
if (_type == Output)
{
throw 0; // Should probably throw a real exception here
}
else // if (_type == Hidden)
{
sigma = 0;
for (int i = 0; i < sigmaCount; i++)
{
sigma += sigmas[i] * weights[i] * derive;
}
sigma *= derive;
}
_deltaWeights[0] += alpha * sigma * 1; // Adjust the BIAS weight //////
for (int i = 1; i < _numOfWeights; i++) // Adjust the other weights
{
_deltaWeights[i] += alpha * sigma * inputs[i - 1];
}
return sigma;
我崩溃了第二个删除[] sigmas; (在第一个代码块的末尾)但是如果sigmas指向由sigmasNext分配的堆,为什么它会崩溃?在保留下一个循环的同时解除分配sigmasNext的正确方法是什么?
答案 0 :(得分:0)
您正在分配一个_M浮动数组
float* sigmasNext = new float[_M];
并写入元素0 .._ H [0]
for (int j = 0; j < _H[0]; j++)
sigmasNext[j] = ...
分别写出元素0 .._ H [i]
for (int j = 0; j < _H[i]; j++)
sigmasNext[j] = ...
我猜你正在向数组中写入多于_M个元素,从而破坏了内存管理结构,从而导致delete []
崩溃。
如果你没有使用原始指针而是使用像vector这样的STL容器,那就不会发生这种情况。 vector将在调试模式下断言,并告诉您是否访问无效索引处的元素。