Segmentation Fault and I don't know why.

So the following piece of code gives me a segmentation fault and I can't figure out for the life of me why. What I'm trying to do is basically build a pool from population the has tickets. When a ticket is more than zero tickets then the population gets added the the mating pool and it continues.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
void buildMatingPool(int matingFactor, double populationFitness[],double matingPool[]){
    int i;
    int j = -1;
    int num1 = 0;
    double tickets;
    double ticketI[] = {};
    int population[] = {};

    for(i = 0; i < 200; i++){
        population[i] = i;
    }
    for (i = 0; i < 200; i++){
       
        tickets = 0;
        tickets = populationFitness[i] * matingFactor;
        ticketI[i] = tickets;
    }
    for(i = 0; i < 200; i++){
       if(ticketI[i] > 0){
          matingPool[j] = population[i];
          j = j + 1;        
       }
       else(ticketI[i] == 0){
          j = j;        
       }
    }
 }
1
2
3
4
5
int population[] = {};

    for(i = 0; i < 200; i++){
        population[i] = i;
    }


You are attempting to write to array elements population[0] to population[199]. How big is the array population? Does it have that many elements in it?

What happens if you try to write to an array element that doesn't exist? Something very bad...


While I'm here, don't use arrays. Don't use arrays. Don't use arrays. Use vectors. Use vectors. Use vectors.
Last edited on
You initialise your arrays to have zero length, at lines 6 and 7. I believe this is illegal, so you automatically have undefined behaviour. However, even if it were legal, every attempt to access an element of those arrays (e.g. lines 10, 16, 19, 20) would be reading/writing beyond the end of those arrays.

@MikeyBoy and @Repeater y'all nailed it right on the head. What I didn't realize when I wrote this was that the array size wasn't specified and it would cause me problems. Thank You for y'alls help. I feel very dumb lol.
No worries - glad I could help!
Topic archived. No new replies allowed.