title: Segmentation fault in C while declaring large pointer array
body: <p>I run in a problem with a program and I'm not sure how to solve it. I'm processing a file and to do so I get the size with ftell and store it in M_size. After that I declare a unsigned char pointer array with N. The array is then used in two functions a() and b().</p>
  
  <pre><code>...
  unsigned long N = (M_size/ x);
  int LstElemSize = M_size % x;
  if(LstElemSize != 0){
      N += 1;
  }    
  unsigned char *ptr_M[N]
  a(ptr_M)
  b(ptr_M)
  ...
  </code></pre>
  
  <p>Function a() actually initializes each element of ptr_M in a for loop:</p>
  
  <pre><code>a(){
    int i;
    for(i = 0; i &lt; N-1; i ++){
       ptr_M[i] = malloc(sizeof(unsigned char) * x);
    }
   }
  </code></pre>
  
  <p>Function b() iterates then over each element and calculates stuff and at the end each element is freed.</p>
  
  <p>My problem is now that when I try to process a file e.g. 1 GB the array size will be around 4 000 000 and a Segmentation error occurs (In the line i declare my array). If I calculated it correctly that is 8 byte (char pointer) times 4 000 000 = 32MB. The server running the program has enough memory to hold the file, but i guess as mentioned in <a href="https://stackoverflow.com/questions/15283546/segmentation-fault-while-creating-large-arrays-in-c">Response 1</a> the stack space is not enough. </p>
  
  <p>What can I do to solve my problem? Increase my stack space? Thanks!</p>