-1

I did some experiments by using a function call and declaring my matrix in a function and use to write '1' in every row and column. However after some time the program crashes and stops working.

example one: The matrix is declared every time it is called in a while loop

void func(int row, int col){
int matrix[row][col];

for....
write one in the matrix...
}

example two: The matrix is declared outside the function as a global

int matrix[row][col];
void func(){


for....
write one in the matrix...
}

main code

int main(){
      while(1){
        func(...);

      }
}

My question to you is that my code crashes whenever my matrix is declared inside a function but does not crash whenever it is declared outside a function. Do you guys know why the problem is like this ? Isnt the matrix a temporal value in the function , meaning will it not be erased after the function has executed ?

bopia
  • 59
  • 1
  • 6

1 Answers1

-1

When declared within the function the matrix is allocated inside the stack. If your matrix gets big enough it will try to read/write outside the stack and cause a segmentation fault. Declaring it outside any function it is statically allocated and it is allocated within your executable (more details here).

Community
  • 1
  • 1
hiddenbit
  • 333
  • 1
  • 2
  • 11
  • yeah you are correct, whenever I checked my data I could compile but my data that I needed was another variable strange enough. So the problem here was that my matrix [100][100] was to big = 100*100 * 4(bytes)= 40000 bytes, then this can give some segmentation fault. – bopia Feb 24 '16 at 19:27