0

This small C program is crashing every single time.

It is supposed to allocate a chunk of memory under the form of a 3D grid composed of many structures (cells) disposed in memory in a 3D-friendly pattern. The structs will be populated with position data.

I don't know why it crashes. It returns this number: c0000005.

#include <stdio.h>
#include <malloc.h>

typedef struct {
int coords[3];
} cell;

int main() {

    int x=4, y=8, z=6;

    int volume=x*y*z;

    cell *arr=(cell*)calloc(volume,sizeof(cell));

    int u=0,v=0,w=0;
    int index;

    for (w=0; w<z; w++) {
    for (v=0; v<y; v++) {
    for (u=0; u<x; u++) {

        //printf("%d %d %d\n", u, v, w);

        index=u+v*y+w*y*z;

        arr[index].coords[0]=u;
        arr[index].coords[1]=v;
        arr[index].coords[2]=w;

        //getchar();

    }}}

    printf("All done.\n");

    return 0;
}
user2464424
  • 1,536
  • 1
  • 14
  • 28

1 Answers1

2

The problem is index=u+v*y+w*y*z;.

It should be index=u+v*x+w*y*x;.

So @nos is right. It triggers a segmentation fault because 6=z>x=4 and index becomes too large.

francis
  • 9,525
  • 2
  • 25
  • 41