Home > Software engineering >  Limit for memory allocation to an array on stack in C?
Limit for memory allocation to an array on stack in C?

Time:04-21

I don't know how to ask this question as it was little confusing to me. i was having a problem with this code

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

#define ull unsigned long long

#define SIZE 1000000001

#define min(a,b) ((a<b?a:b))
#define max(a,b) ((a>b?a:b))

int solve(void) {

//    unsigned *count = malloc(sizeof(unsigned) * SIZE);
    int k;
    scanf("%d", &k);
    unsigned count[SIZE];
    for (ull i = 0; i < SIZE; i  ){
        count[i] = 0;
    }

    return 0;
}

int main(void){
    unsigned t;
    if (scanf("%u", &t) != 1) return 1;
    while (t-- > 0){
        if (solve() != 0) return 1;
    }
}

This code for me is giving segfault.

What my observation is

  1. it is running fine until it is in solve function.
  2. on calling solve function it is giving segfault.
  3. It has nothing to do with scanf("%d", &k) as by removing this line gives the same error
  4. But if we decrease the SIZE value it will run fine.
  5. Other thing which i can do is instead of creating an array on stack i can use heap and this is working fine.
  6. If i only declare array count in solve function instead of taking k as input and initializing all the values of array count to 0. i am not getting any segfault

So i have some questions regarding this.

  • Is this due to memory limitation to array or because of memory limitation for a stack frame for the function solve (or possibly another reason which i can't find).
  • If this is due to any kind of memory limitation than isn't it is too low for a program?
  • How compiler checks for such errors as adding any kind of print statement won't run before array declaration as i am getting segfault when program reaches solve. So compiler somehow knows that their is a problem with code without even getting there.
  • and specifically for the 6th point, as per my knowledge when declaring array it reserves memory for the array. So by initializing it i am doing nothing which will increase the size of array. So why i am not getting any kind of error when declaring array while i am getting segfault when i am initializing all those values in array

Maybe i am seeing it in totally wrong way but this is how i think it is, So please if you know any reason for this please answer me about that too

CodePudding user response:

It depends on your operating system. On Windows, the typical maximum size for a stack is 1MB, whereas it is 8MB on a typical modern Linux, although those values are adjustable in various ways. For me it's working properly check with other platform or other system.

  • Related