Treesrule14
Treesrule14

Reputation: 711

Illegal instruction upon operating on an array

Okay so I am trying to make a histogram from a three dimensional array of int in c. Here is the line where I edit the array;

buckets[(int)floor(x/splits)][(int)floor(y/splits)][(int)floor(z/splits)]++;

x, y, z were generated earlier in the program (this is in a loop) splits was asked as input from the user. Then I try to put this data into a histogram and the compiler is giving me an illegal instruction.

histogram[(int)buckets[i][j][k]]++;

I am pretty sure it is here because I put print statements in the program which worked until this point but not afterwords. Here is all of the relavent code.

    ff=fopen(fname,"r");
int buckets[split][split][split];
splits = (double) 1/split;
for(i=0; i<split; i++){
    fscanf(ff,"%lf",&x);
    fscanf(ff,"%lf",&y);
    fscanf(ff,"%lf",&z);
    buckets[(int)floor(x/splits)][(int)floor(y/splits)][(int)floor(z/splits)]++;    
    fclose(ff);  
}
int histogram[10];
for (i=0; i<split; i++) {
    for (j=0; j<split; j++){
        for(k=0;k<split;k++){
            histogram[(int)buckets[i][j][k]]++;
        }
    }
}

Upvotes: 0

Views: 803

Answers (2)

gravitron
gravitron

Reputation: 3604

When you define your array:

int buckets[split][split][split];

You do not initialize it with something like:

memset(buckets, 0x00, sizeof(int) * split * split * split);

So buckets has unknown values in it. You then increment these numbers, but when you do:

histogram[(int)buckets[i][j][k]]++;

buckets[i][j][k] could be equal to anything. Solution is to add the memset() after the array declaration.

Upvotes: 1

Sangeeth Saravanaraj
Sangeeth Saravanaraj

Reputation: 16597

Please share the actual values of the variables during run-time (using gdb) - split, x, y, z and splits.

If you see the correct values initially and suddenly seeing an abnormality, then you may be hitting a stack overflow. So try using dynamic memory allocation (which uses heap). Please try to use valgrind to detect any memory leaks.

Upvotes: 0

Related Questions