Temitope.A
Temitope.A

Reputation: 123

Strange segmentation fault

I've defined a random function (int random(int sup, int seed)) which returns a value between 0 and sup-1. I've defined a struct, point, of which pos_parents and population are 2-dimensional arrays. The swap functions swap elements of the v array, which is a array of "indexes". All is done in order to sort out par_n members into pos_parents out of population members without sorting twice the same member.

This gives segmentation fault.

If I replace the variable r inside population[v[r]][j] with an explicit value, then it all functions. How is this possible? I've tried the random function and it doesn't seem to have any problem.

In addition, when segmentation fault occours, printf won't even activate for the first loop.

point population[pop_size][array_size];
point pos_parents[4*par_n][array_size];
int v[pop_size];

for (i=0; i<4*par_n;i++)
    v[i]=i;

for(t=0;t<time_limit;t++) //The cycle of life
{
    for(i=0;i<4*par_n;i++)
    {
        r=random(pop_size-i,i);
        printf("%d\t",r);

        for(j=0;j<array_size;j++)
        {
            pos_parents[i][j]=population[v[r]][j];
        }
        swap(&(v[r]),&(v[pop_size-1-i]));
    }

When executing i type 3(route locations-array size), 8(pop_size), 1(time limit), 1 (par_n)

This is the entire code (less than 150 lines), always insert 1 to time_limit, because I haven't still completed the cycle. https://docs.google.com/open?id=0ByylOngTmkJddVZqbGs1cS1IZkE

P.S. I'm trying to write an evolutionary algorithm, for route optimization

Upvotes: 0

Views: 140

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 476930

The loop with v[i] = i; goes from 0 to 4 * par_n, but v is an array of size pop_size. That looks like an out-of-bounds problem waiting to strike. And the same again for the counter i in r = random(pop_size - i, i);, since i is used in v[i].

Upvotes: 1

Related Questions