tycoon
tycoon

Reputation: 131

Limit for memory allocation to an array on stack in C?

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.

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

Upvotes: 1

Views: 651

Answers (1)

Revanth N Mallol
Revanth N Mallol

Reputation: 56

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.

Upvotes: 4

Related Questions