herteladrian herteladrian - 1 year ago 70
C++ Question

Segmentation fault: 11 when using dynamic 3D array parameter

using gdb to find the source of the Seg Fault I get this

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;
matchCounters(/*some more parameters here*/ all_counters[0]);


accessing counters here causes a segmentation fault: 11

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

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


accessing counters here works just fine

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;


Answer Source
all_counters = new double ** [2];

The all_counters parameter is passed by value to generateCounters().

This allocates a new array in dynamic scope, and assigns it to the parameter named "all_counters", in the function called generateCounters().

The all_counters in your main() is not affected at all.

Instead of passing it by value, you should, instead, declare it in generateCounters(), return it from the function, and assign it to the variable in main().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download