Search code examples
c++linuxcygwin

Segmentation fault in class


#include <iostream>    
using namespace std;    
class Bucket{

    public:
        Bucket();
        void setN(int n);
        void setArrayb();
        void storeArray(int s, int cc, int **A);
        int showdata(int cc);
    private:
        int n_elements;
        int *b;

    };
    Bucket :: Bucket(){

        ;
    }
    void Bucket :: setN(int n)
        {
            n_elements = n;
        }

    void Bucket :: setArrayb(){

        int *b = new int [n_elements + 1];     
      }

    void Bucket :: storeArray(int s, int cc, int **A){


         cout << this -> n_elements;
        if(cc <= n_elements){
            this -> b[cc] = A[0][s];
        }

    }

    int Bucket :: showdata(int cc){
        return this -> b[cc];
    }

int main(){

    int n = 10;
    int** A = new int*[1];
    for (int i = 0 ; i < 1 ; i++){
        A[i] = new int [n + 1];
    }

    Bucket B[n + 1];
    A[0][3] = 6;

    int fb = 10;
    B[1].setN(fb) ;
    B[1].setArrayb();
    B[1].storeArray(3, 1, A);
    cout << B[1].showdata(1);
}

I'm trying to complete bucketsort with n bucket for A. n_element is the numbers of each bucket, after compiling, it's legal. But when I execute it, it cause segmentation fault.Can someone explain what happened in this code?

Using in linux environment by cygwin.


Solution

  • Your problem is caused by your misunderstanding of what the following line does in setArrayb.

    int *b = new int [n_elements + 1];     
    
    1. It initializes a function local variable b.
    2. It does not do anything to the member variable of the same name.
    3. It leaks memory.

    When you access the elements of the member variable b in storeArray, you access an uninitialized pointer, which causes undefined behavior.

    Change that line to

    b = new int [n_elements + 1];     
    

    Unless there is a need for you to manage dynamically allocated memory in your code, change your class to use std::vector<int>.

    If you must manage your own memory, please follow The Rule of Three.