2

I have this code which segfaults when run.

#include <stdlib.h> // size_t

int main()
{
    size_t s = 0xFFF;
    char a[ s * s ];

    a[ 0 ] = 'a';

    return 0;
}

When I change the value of variable s to 0xFF it works correctly.

How can I determine the maximum possible size of an array in a portable way?

I use 64 bit linux and code is compiled with

gcc file.c

Update:

I do understand that large objects should be allocated with malloc() and small arrays can be allocated locally on the stack. However I want to know exactly how large these small arrays can be. I also want the solution to be portable.

Also, what if I have some other stuff on stack before my array is allocated? In that case, the maximum size of stack can't be used as the size of my array, because the stack will overflow.

Babken Vardanyan
  • 14,090
  • 13
  • 68
  • 87

3 Answers3

2

The problem is not cause by "the maximum size of arrays" (I don't think such limits even exist), but by the limit of stack size, as you're declaring the array on the stack.

If you're on Linux, there is getrlimit to query with. Also you may find getrusage helpful. However I believe for large items they shall be allocated on the heap (via something like malloc).

For changing the maximum stack size, see Change stack size for a C++ application in Linux during compilation with GNU compiler

Community
  • 1
  • 1
starrify
  • 14,307
  • 5
  • 33
  • 50
1

That is not a question of maxim array size, is a question of maximum stack frame size. The max size will depend on OS, arhitecture and max stack size. For example on Linux you can adjust it with setrlimi(LIMIT_STACK,...) and on Windows there are several means to control it, see Thread Stack Size.

But none of these really apply. If you want to allocate a large array, allocate it from the heap, not on the stack.

Remus Rusanu
  • 288,378
  • 40
  • 442
  • 569
0

array locates in stack. You may check the default stack size with command ulimit -s. Say, ulimit -s tells your that stack size is 1024 bytes (in reality it should be some value like 8MB), in your case, s uses 8 bytes, so a can be at maximum 1016 bytes then.

TieDad
  • 9,143
  • 5
  • 32
  • 58