0

I had some problems with an array of structs, so I wrote the following just to make a test:

#include <stdio.h>
 
#define MAX_NAME_LEN 16
#define MAX_VALUE_LEN 32
#define MAX_ELEMS_IN_BLOCK 16
 
#define MAX_BLOCKS_IN_FILE 4096
 
typedef struct massElem_t{
     char name[MAX_NAME_LEN];
     char value[MAX_VALUE_LEN];
} massElem_t;
 
typedef struct massBlock_t{
     massElem_t header;
     massElem_t rest[MAX_ELEMS_IN_BLOCK-1];
} massBlock_t;
 
 
 
int main(){
     
     massBlock_t massFile[MAX_BLOCKS_IN_FILE]; /* should be 3,145,728 bytes */
     
     printf("==arrays and variables declared\n");
     
     return 0;}

I'm compiling it with

gcc -g0 arraytest.c -o arraytest.exe -Wall -Wextra -Wshadow -Wvla -pedantic-errors -ansi

It compiles successfully, but upon execution, it takes some seconds, and quits without errors, and without even printing the printf line. The array doesn't get allocated, or its allocation causes some (not reported) error. If I halve the array size (eg. defining MAX_ELEMS_IN_BLOCK as 8 instead of 16), it runs fine.

I tried compiling on linux to use libasan:

gcc -ansi -g3 -static-libasan -fsanitize=address -Wall -Wextra -Wshadow -Wvla -pedantic-errors -o arraytest arraysize.c

Again, it compiles successfully, and also runs correctly. To obtain an error on linux I have to make the size of the array 4 times bigger, for example defining MAX_ELEMS_IN_BLOCK as 64 instead of 16. That makes the final array of size 12,582,912 bytes. Libasan detects a stack overflow.

My question is: why the difference between win10 and linux? Is there a way to allocate such an array?

Thanks

nff
  • 33
  • 5
  • 1
    You're overflowing the maximum size of a stack frame by creating it as a local array. – Barmar Nov 14 '20 at 15:01
  • However, if you use `calloc` to dynamically allocate your array on the heap, you can create as big an array as can fit in memory. – erik258 Nov 14 '20 at 15:07
  • thanks @Barmar and daniel-farrell , I tried with calloc and now it works perfectly. Some considerations: how do I decide stack vs heap for a large array? I usually would like to avoid malloc/calloc, and I also think deciding stack vs heap based on hardware is not really a good practice, nor portable. Using calloc makes it portable, allocating on the stack when possible makes it a deterministic allocation. BUT, if I only use calloc with a constant size at the beginning of my program and free it just before exiting, it should be equally deterministic, ?? Is there a way to check for that? – nff Nov 14 '20 at 17:07
  • Usually you use stack for data that's only needed during the function, and heap for data with dynamic lifetimes. But if the data is really large you have to use heap. – Barmar Nov 14 '20 at 20:46

0 Answers0