1

If I keep the value of rows to 100000, the program works fine but, if I make rows one million as 1000000, the program gives me segmentation fault. What is the reason? I am running below on Linux 2.6x RHEL kernel.

#include<stdio.h>

#define ROWS 1000000
#define COLS 4

int main(int args, char ** argv)
{
  int matrix[ROWS][COLS];

  for(int col=0;col<COLS;col++)
  for(int row=0;row < ROWS; row++)
    matrix[row][col] = row*col;

  return 0;
}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Jimm
  • 8,165
  • 16
  • 69
  • 118
  • 3
    Stackoverflow on Stack Overflow... – Mysticial Mar 01 '13 at 19:47
  • Sadly there's no way to catch such allocation failures at compile time. Try to use as small an array as possible. If you are not sure, then it's likely you don't have enough stack space ;-) – P.P Mar 01 '13 at 20:01

3 Answers3

4

The matrix is a local variable inside your main function. So it is "allocated" on the machine call stack.

This stack has some limits.

You should make your matrix a global or static variable or make it a pointer and heap-allocate (with e.g. calloc or malloc) the memory zone. Don't forget that calloc or malloc may fail (by returning NULL).

A better reason to heap-allocate such a thing is that the dimensions of the matrix should really be a variable or some input. There are few reasons to wire-in the dimensions in the source code.

Heuristic: don't have a local frame (cumulated sum of local variables' sizes) bigger than a kilobyte or two.

[of course, there are valid exceptions to that heuristic]

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
2

You are allocating a stack variable, the stack of each program is limited.

When you try to allocate too much stack memory, your kernel will kill your program by sending it a SEGV signal, aka segmentation fault.

If you want to allocate bigger chunks of memory, use malloc, this function will get memory from the heap.

Intrepidd
  • 19,772
  • 6
  • 55
  • 63
1

Your system must not allow you to make a stack allocation that large. Make matrix global or use dynamic allocation (via malloc and free) and you should be ok.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469