2

I try to make array of structs. Struct contain two 2-dimensional arrays (100x100). If i want to make array of 30 or more structs the error occur - "Segmentation fault". I'm using CodeBlocks with MINGW compiler. Code:

struct gracze
{
    int pole1[100][100];
    int pole2[100][100];
};


int main()
{
    gracze gracz[30];

return 0;
}
A. Kwas
  • 27
  • 7
  • Most likely this title has nothing to do with the problem. You need to show your code. You should also use a debugger to get a backtrace. – Chris Beck Sep 01 '15 at 15:50
  • Does this happen if all your source contains is the definition of the struct and a `main()` with the array? If yes, show us the code. If not, **why not**? – DevSolar Sep 01 '15 at 15:51
  • Generally speaking, the limit on the size of pointers and arrays is environment specific (64-bit vs 32-bit) and has little to do with C++ itself. – Xirema Sep 01 '15 at 15:51
  • What is your stack limit? Your struct would take approximately 4 * 100 * 100 * 2 * 30 = 2 400 000 - 2 MB. Do you set your stack size to something lower than that? – SergeyA Sep 01 '15 at 15:53
  • I didn't change stack limit – A. Kwas Sep 01 '15 at 15:55
  • A Kwas: JSF's answer is correct, the reason is that stack size is limited, usually like 8 MB or something by default. – Chris Beck Sep 01 '15 at 15:55
  • Generic code review remark: Keeping your identifiers in English is making things easier if there is *any* chance of your code being seen by other people (either because your company is hiring abroad, your project might be open source some day, or you intend to post questions on SO). Didn't really matter in this case, but I know I get tired of second-guessing the meaning of localized identifiers *really* quick. ;-) – DevSolar Sep 01 '15 at 16:07

2 Answers2

2

You are allocating about 2.4 to 4.8 megabytes of stack space.

IIRC, the default stack size of MinGW is about 2 MB, i.e. you are exceeding your stack space, and need to increase it -- if, indeed, you want to go with such a large stack allocation instead of e.g. dynamically allocating the memory:

#include <stdlib.h>

int main()
{
    gracze * gracz;
    if ( ( gracz = malloc( sizeof( gracze ) * 30 ) ) != NULL )
    {
        // stuff
        free( gracze );
    }
    return 0;
}

If that is not what you are looking for, this SO question covers the "how" of increasing stack space (gcc -Wl,--stack,<size>).

On Linux, there is also the global limit set by ulimit -s.

This SuperUser question covers Windows / VisualStudio (editbin /STACK:reserve[,commit] program.exe).

Community
  • 1
  • 1
DevSolar
  • 67,862
  • 21
  • 134
  • 209
1

You are doing a large allocation on the stack. Either increase the stack size, or allocate the object some other way (static or malloc).

See

DevC++ (Mingw) Stack Limit

Community
  • 1
  • 1
JSF
  • 5,281
  • 1
  • 13
  • 20