首页 > 解决方案 > 类中的分段错误

问题描述

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

我正在尝试用n桶为A完成桶排序。n_element是每个桶的数量,编译后是合法的。但是当我执行它时,它会导致分段错误。有人可以解释这段代码中发生了什么吗?

通过cygwin在linux环境下使用。

标签: c++linuxcygwin

解决方案


您的问题是由于您对以下行在setArrayb.

int *b = new int [n_elements + 1];     
  1. 它初始化一个函数局部变量b
  2. 它不对同名的成员变量做任何事情。
  3. 它泄漏内存。

当您访问成员变量bin的元素时storeArray,您访问的是一个未初始化的指针,这会导致未定义的行为。

将该行更改为

b = new int [n_elements + 1];     

除非您需要在代码中管理动态分配的内存,否则请将您的类更改为使用std::vector<int>.

如果您必须管理自己的记忆,请遵循“三法则”


推荐阅读