I get a segmentation fault on this code at a different line every time. C++ -
i writing genetic algorithm program. use linux (os), c++ (language) , g++ (compiler). following code generates seg fault. problem run 50+ times , times none. plus error occurs in of tmp[ k ][ p ] or tmp[ k + 1 ][ p ] assignment lines. missing here?
int** geneticalgorythm::newgeneration( int** parents ) { int** tmp = new int*[ population ]; int p = 0; for( int k = 0; k < population; k += 2 ) { tmp[ k ] = new int[ ngenes ]; tmp[ k + 1 ] = new int[ ngenes ]; setlikelihood( parents ); int parent1 = getparent( likelyhood ); int parent2 = getparent( likelyhood ); while( parent1 == parent2 ) { parent2 = getparent( likelyhood ); } for( p = 0; p < crossoverpoint; p++ ) { tmp[ k ][ p ] = parents[ parent1 ][ p ]; tmp[ k + 1 ][ p ] = parents[ parent2 ][ p ]; } for( p = crossoverpoint; p < ngenes; p++ ) { tmp[ k ][ p ] = parents[ parent2 ][ p ]; tmp[ k + 1 ][ p ] = parents[ parent1 ][ p ]; } } currgeneration++; return tmp; } int geneticalgorythm::getparent( double* lh ) { int randval = rand( ) % 100; int* choose = new int[ 100 ]; int counter = 0; for( int k = 0; k < population; k++ ) { for( int j = 0; j < (int)likelyhood[ k ]; j++ ) { choose[ counter++ ] = j; } } counter = choose[ randval ]; delete[] choose; return counter; } void geneticalgorythm::setlikelihood( int** pg ) { multipleinverse = 0; double 1 = 1.00; for( int mi = 0; mi < population; mi++ ) { multipleinverse += one/checkfitness( pg[ mi ] ); } for( int lh = 0; lh < population; lh++ ) { likelyhood[ lh ] = round(((one/checkfitness( pg[ lh ] ))/multipleinverse) * 100); } }
variable values: population = 20; ngenes = 3; crossoverpoint = 1;
likelihood how parent selected based on fitness level. pg parent genes. [ population ][ ngenes ].
thanks in advance.
looking @ values provided, looks indexing tmp
ok. if lines you're seeing segfault
tmp[ k ][ p ] = parents[ parent1 ][ p ]; tmp[ k + 1 ][ p ] = parents[ parent2 ][ p ];
it have because of indexing parents
[ parentn ][ p ]
. dimensions of parents
? getparent(…)
guaranteed return valid index parents
?
Comments
Post a Comment