Search code examples
cpointerssegmentation-faultmemory-corruption

Segmentation Fault and Memory Corruption with pointer to array of pointers


The objective here is to have a pointer that works like a 2D matrix. I've tested the following bit of code for creating a pointer to and array of integer pointers. It compiles and runs fine. (This is a simplified version, I've tried assigning/printing values to mymatrix[x][y] and it works fine.)

#include <iostream>
int **mymatrix;

int main(int argc, char* args[]){

  mymatrix = new  int*[100] ;
  for( int n = 0; n <= 100; n++ ){
    mymatrix[n] = new int[200] ;
  }
  return 0;
}

However, as soon as I copy this snippet to another code (which previously ran fine), the code still compiles but fails to run. There are no errors or warnings related to this snippet. This is weird because mymatrix doesn't even interact with the rest of the code yet (after being defined it's just never used again).

The actual error which interrupts the execution varies between crashing when trying to load a font, Segmentation Fault when trying to assign a value, and Memory Corruption (with a huge log output of what I think are threads).

I could paste sections of the larger code, but I'm almost convinced that this is all happening because I'm not defining this pointer in the proper way. Am I doing something clumsy or unsafe here? Or should I start looking through the rest of my code for bugs?


Solution

  • for( int n = 0; n <= 100; n++ )
    

    This causes an array overrun. mymatrix[100] is not part of the mymatrix array. The result of writing to it is undefined. The reason it "works fine" by itself is that there aren't other data structures for you to clobber. The for loop should start with.

    for( int n = 0; n < 100; n++ )
    

    In general the use of <= in for loop conditions is not idiomatic c. If you find yourself using it, you should ask yourself if you are really doing the right thing. Array overruns are sometimes hard to find. If you are on linux, you can use a tool like valgrind to help you identify this and other errors.