declaring an array of 1000000 size

I was seeing a solution of a problem

in the solution an array is declared as

int vec[1000000]

when i copied the code and tried to run it on my system it gives me error
but when i submitted the same code on codechef i got correct answer.

while searching for the cause i found out that i cant declare array of that size because stack memory is limited.
i should declare it in heap using dynamic memory allocation
but my question is that how i got correct answer on codechef ?

Hello,

It might be possible that your compiler flags are somewhat “ill-defined”, in the sense that you don’t allow so much stack memory to be used which basically means your stack-size has a different size limit than the one used by Codechef judge, but, I compiled that code in my system and it gave no errors or warnings…

I am using this to compile it:

gcc -Wall -ansi -pedantic -o teste teste.c -lm

This is my gcc version status:

gcc (Ubuntu/Linaro 4.7.3-1ubuntu1) 4.7.3
Copyright (C) 2012 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

You should re-check your compiler settings, as if the code works fine on my system and on Codechef, then the problem must be on your side…

Hope this helps!!

Best regards,

Bruno

1 Like

when i checked my gcc version
it showed

gcc 3.4.2

copyright © 2004

i think its too old and that’s why its stack memory will be less than its current version.
thanks alot

I’m glad I could help you :slight_smile:

I’m not saying this will totally work and solve your problem but, if you declare your array globally then, i think even on old gcc compiler this will work.

2 Likes

yes its working.
but y?

Global variables are allocated in the heap memory, which is the memory where dynamically allocated memory resides.
Non-global variables are allocated in the stack which is typically much, much shorter… This a good trick to have present as it might help you even with newer compiler versions… :slight_smile:

2 Likes

I was having same problem while compiling some problem of codechef, but when i submitted it, got ac…

@abcdexter24 read my answer first

same as @kuruma

thanks it helped me in clearing some basic concepts…:slight_smile: