-1

I was working on a C++ program to implement a neural network.

But I cant figure out why this code produces a segmentation fault.

class Node{

public:

    //Creating Vectors for weights and biases
    vector<double> weights;
    
    double biasN;

    //Constructor
    Node(int numNodeIn){

        //The Loop enters all the inputs and weights from the array into their respective vectors
        for (int i = 0; i < numNodeIn; i++)
        {
            double z = (double)(rand() % 100) /100;;
            cout << z<<"##"<<endl;
            weights.push_back(z);
            
            
        }
        
        //The bias value of a particular Node
        biasN = (double)(rand() % 1000) /100;
        cout << biasN<<"#"<<endl;
    }
};


class Layer{
public:

    //Vars
    int numNodesIn,numNodesOut;
    vector<Node> nodes;
    
    Layer(int NodesIn,int NodesOut){
        this->numNodesIn = NodesIn;
        this->numNodesOut = NodesOut;

        //Creates and adds Nodes as per requirement
        for (int i = 0; i < numNodesOut; i++)
        {

            //Creates a object of class Node
            Node N(numNodesIn);

            //Adds the object in the vector
            nodes.push_back(N);


        }
        
    }
    double* calcOutput(double inputs[]){
        //Dynamic array for storing weighted inputs after computation
        double *weightedInputs = new double(numNodesOut);

        //For loop to iterate over the Outnodes and compute weighted inputs
        for (int nodeOut = 0; nodeOut < numNodesOut; nodeOut++)
        {
            // Adding Bias to the weighted input
            double weightedInput = nodes[nodeOut].biasN;

            // Adding all the inputs multiplied with weights 
            for (int nodeIn = 0; nodeIn < numNodesIn; nodeIn++)
            {
                weightedInput += inputs[nodeOut] * nodes[nodeOut].weights[nodeIn];
            }
            weightedInputs[nodeOut] = weightedInput;


        }
        return weightedInputs;
    }
};
//Main Function
int main() {
  
//   long double out =  input[0]*weight[0] + input[1]*weight[1] + input[2]*weight[2] + input[3]*weight[3] + input[4]*weight[4] + bias[0];

    // Setting random seed as current time
    srand (static_cast <unsigned> (time(0)));

    const int hiddenLayers = 4;

    // Vars for testing
    Layer layer(3,hiddenLayers) ;
    double inp[3] = {2.5,2.5,1.5};
    double *out = layer.calcOutput(inp);

    // Printing the result
    for (int i = 0; i < hiddenLayers; i++)
    {
        cout << out[i]<< endl;
    }

    delete [] out;
    
}

When run without the srand time seed update it produces a make: *** [Makefile:22: run] Segmentation fault.

When run with the srand seed update it produces a munmap_chunk(): invalid pointer.

The segmentation fault as well invalid pointer error occur after all the values have been printed. It seems that the error occurs after all the computations are done. I have not tested with a debugger yet since I have never used a c++ debugger before.

Any help would be appreciated. Thanks in advance for looking through the long code.

I tried replacing all the parts of the code that could be problematic but nothing seems to help.

273K
  • 29,503
  • 10
  • 41
  • 64
  • 3
    It's good time to start using a debugger. – 273K Feb 24 '23 at 06:56
  • 1
    You are mixing "C" style and "C++ style programming why use `double* calcOutput(double inputs[]){` instead of `double calcOutput(const std::vector& inputs)` . In C++ avoid pointers unless you really need them (polymorphism, or very dynamic runtime lifetime) – Pepijn Kramer Feb 24 '23 at 07:07
  • My advice learn a bit more C++ first, and indeed learn to use a debugger. Good sources to learn cpp from are : A [recent C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) or have a go at https://www.learncpp.com/ (that's pretty decent, and pretty up-to-date). For C++ reference material use : [cppreference](https://en.cppreference.com/w/). And after you learned the C++ basics from those sources, look at the [C++ coreguidelines](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines) regularely to keep up-to-date. – Pepijn Kramer Feb 24 '23 at 07:08
  • Yeah,my bad... I am experienced in C thats why I used pointers. Its just simpler for me – Soumish Das Feb 24 '23 at 09:12
  • Thnx for ur advice btw – Soumish Das Feb 24 '23 at 09:12

1 Answers1

2

One simple error is

double *weightedInputs = new double(numNodesOut);

which should be

double *weightedInputs = new double[numNodesOut];

But as stated in the comments avoid new and pointers altogether. weightedInputs should be a vector and calcOutput should return that vector.

As someone here once said. in C++ 'dynamic array' is spelled std::vector.

john
  • 85,011
  • 4
  • 57
  • 81