0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define     MAXNO   1000

typedef struct
{
    int     n;
    char    site[4];
} stru;

typedef struct
{
    stru t1[MAXNO];
    stru t2[MAXNO];
} struall;

int main()
{
    struall tmp;
    int i;
    printf("%d\n",i);
    return 1;
}

Hi everyone, I am trying to declare a structure variable which has two structure array members inside it. If the array size (MAXNO) is small, i can compile successfully. However, if the array size is very large (define MAXNO as 1000000), the declaration fails with segmentation fault.

Can anyone tell me the reason?

Thanks a lot!

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
Toga
  • 19
  • 2

1 Answers1

2

You can only fit "oh-so-much" onto the machine stack. Try:

struall* tmp = malloc(sizeof(struall));

in C or one of the following for C++:

struall* tmp = new struall; // C++03
std::unique_ptr<struall> tmp{new struall}; // C++11
auto tmp = std::make_unique<struall>(); // C++14
kirbyfan64sos
  • 10,377
  • 6
  • 54
  • 75
  • Nice and complete :-) A bit of explanation about each method will give you a fanbase for this one I guess..nbd though.. – sjsam Jul 06 '16 at 02:41