简体   繁体   中英

Segfault occurring when using erase on a vector

I'm writing some basic neural network tools for a larger scale project I'm working on.

the neural network itself is made up of vectors of different structs and for one function I want it to delete a neuron from a specified layer. Whenever I use the function it works correctly until it removes the neuron's edge that go to the neurons into the next layer (layer+1) which is causing a segfault.

void NeuralNetwork::deleteNeuron(int t_layer, int t_neuronToDelete){
  if(t_layer < 0 || t_layer >= neuralNetwork.size())
    throw LayerDoesNotExistException();

  int numOfNeurons = neuralNetwork[t_layer].neurons.size();
  if(t_neuronToDelete < 0 || t_neuronToDelete >= numOfNeurons)
    throw NeuronDoesNotExistException();
  //delete neuron

//removes neuron
neuralNetwork[t_layer].neurons.erase(neuralNetwork[t_layer].neurons.begin() + t_neuronToDelete);

//remove its edge from neurons to the right
  if(t_layer != neuralNetwork.size())//doesnt let it remove edges if its the output layer
    for(int i=0; i < neuralNetwork[t_layer+1].neurons.size(); i++){
      std::vector<double*>::iterator it = neuralNetwork[t_layer+1].neurons[i].pWeights.begin() + t_neuronToDelete;

      //this line segfaults
      neuralNetwork[t_layer+1].neurons[i].pWeights.erase(it);
    }
}

Your if(t_layer != neuralNetwork.size()) check will always be true, because t_layer is less than neuralNetwork.size() (if it wasn't, the previous line's access to neuralNetwork[t_layer] would result in Undefined Behavior).

You probably meant to check

if (t_layer + 1 != neuralNetwork.size())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM