使用gdb查找段错误的来源

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;

主要()
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;

}

最佳答案

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

这将在动态范围内分配一个新数组,并在名为generateCounters()的函数中将其分配给名为“all_counters”的参数。
all_counters中的main()完全不受影响。

与其按值传递,不如改为在generateCounters()中声明它,从函数中对其进行return,然后将其分配给main()中的变量。

关于c++ - 分割错误:使用动态3D数组参数时为11,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40391201/

10-09 13:34