I have the following code:
int width = 10;
int height = 9;
float** matrix = (float**) malloc(height*sizeof(float));
for (unsigned int i = 0; i < height; i++)
matrix[i] = (float*) malloc(width*sizeof(float));
//This works
matrix[6][0] = 3.0f;
for (unsigned int j = 0; j < width; j++) {
for (unsigned int i = 0; i < height; i++) {
//This fails on [6][0]
matrix[i][j] = 3.0f;
}
}
I am attempting to create a 2D array and initialise it however a segmentation fault is received when setting the value of matrix[6][0] within the loop. What I'm finding very strange is that no error is thrown when I set matrix[6][0] outside of the loop. It's my understanding that a segmentation fault occurs when illegal memory is accessed but I cannot find any reason why different memory is being accessed within the loop. I have even examined the assembly code to find out what's happening but I cannot find the problem.
Update: The code was part of a CUDA program (C++) but my brain was half thinking about C and half about C++, hence why it became a mess.