Alex Crim
Alex Crim

Reputation: 57

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);
    }
}

Upvotes: 0

Views: 52

Answers (1)

1201ProgramAlarm
1201ProgramAlarm

Reputation: 32732

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())

Upvotes: 1

Related Questions