分段故障:11使用动态3D阵列参数时

时间:2016-11-02 22:58:56

标签: c++ gdb

使用gdb查找Seg Fault的来源我得到了这个

Program received signal SIGSEGV, Segmentation fault.
0x00000001000082bf in matchCounters (input=..., size=5, 
    valid_entries=0x100020cd0 <VALID_REGIONS>, nums=0x7fff5fbff460, 
    counters=0x100020588 <VTT for std::__1::basic_ifstream<char, std::__1::char_traits<char> >+8>) at akh70P3.cpp:524
524     cout << "counters[4][1] = " << counters[4][1] << endl;

main()的

double *** all_counters;
generateCounters(all_counters);
matchCounters(/*some more parameters here*/ all_counters[0]);

matchCounters()

在此处访问计数器会导致分段错误:11

void matchCounters(/*some more parameters here*/ double ** counters) {

    //this causes segmentation fault 11
    cout << "counters[4][1] = " << counters[4][1] << endl;
}

generateCounters()

在这里访问计数器工作得很好

void generateCounters(double *** all_counters) {
    all_counters = new double ** [2];
    //region counters
    all_counters[0] = new double * [VALID_REGIONS_SIZE];
    //move kind counters
    all_counters[1] = new double * [VALID_MOVE_TYPES_SIZE];
    for(int i = 0; i < VALID_REGIONS_SIZE; i++) {
        all_counters[0][i] = new double [CATEGORIES];
    }
    for(int i = 0; i < VALID_MOVE_TYPES_SIZE; i++) {
        all_counters[1][i] = new double [CATEGORIES];
    }
    //this works just fine! why?
    cout << "all_counters[0][4][1] = " << all_counters[0][4][1] << endl;

}

2 个答案:

答案 0 :(得分:2)

问题是你在函数generateCounters()中实例化数组,但是你按值传递allCounters而不是你需要通过引用或指针传递它。您应该以这种方式更改功能:

void generateCounters(double **** all_counters) {}

或更多C ++风格:

void generateCounters(double ***& all_counters) {}

答案 1 :(得分:2)

DropDownList

ToolStripDropDownMenu参数按值传递给all_counters = new double ** [2];

这将在动态范围内分配一个新数组,并在名为all_counters的函数中将其分配给名为“all_counters”的参数。

generateCounters()中的generateCounters()根本不受影响。

而不是按值传递,而是应该在函数的all_countersmain()中声明它,并将其分配给generateCounters()中的变量。