Benny K
Benny K

Reputation: 2087

Stack overflow when using c array

When I define

void tfooo(){
int arr[SOME_LARGE_NUMBER];
// some code here
}

I am getting stack overflow, but when I add the static keyword

void tfooo(){
static int arr[SOME_LARGE_NUMBER];
// some code here
}

everything is fine.

What is the difference? Isn’t static arrays as opposed to dynamic arrays always defined on the stack?

Upvotes: 4

Views: 156

Answers (2)

user4207183
user4207183

Reputation:

I am generating the assembler code for the static version and non static version, and the only difference is that into the static version the variable does not exist. I think it has been removed because it is not used into my test.

Are you using the variable into the test are you doing? Maybe the optimiser has removed the variable into the static version.

I am using gcc. To build the assembler code, pass the -S argument:

gcc -S main.c

And this is the test code used for the non static version:

#define SOME_LARGE_NUMBER (100000000000000000)

int arr[SOME_LARGE_NUMBER];

int main(const int argc, const char* argv[]) {
    return 0;
}

And this for the static version:

#define SOME_LARGE_NUMBER (100000000000000000)

static int arr[SOME_LARGE_NUMBER];

int main(const int argc, const char* argv[]) {
    return 0;
}

This is the difference I got:

$ diff main.static.s main.nostatic.s 
23a24
>   .comm   _arr,400000000000000000,4 ## @arr

For the information you are providing this is what I can get. Could you paste more details about your code?


EDIT: Into the image attached we can see the memory layout for a windows application. When we use the static modifier into a function, it is stored into the .data segment instead of the stack of the program, because of that you don't get the stack overflow. In compiling time, the size of the array is known, so that, the binary image store enough space for the data. What is the size of your EXE file in both versions? If I am not mistake the EXE file size for the static version will be much bigger than the no static version. I suppose that the size of the array is reserved into the data segment when the binary is loaded. However, when using the no static version, it depends on how much memory is set up the stack. You can modify this size using the flag "/F" when compiling from the command line (see this link https://msdn.microsoft.com/en-us/library/tdkhxaks.aspx). I don't have a VM with windows to double check.

enter image description here

In overview, your static variable is not stored into the stack, because of that you don't get a stack overflow when using the static version.

Upvotes: 1

lost_in_the_source
lost_in_the_source

Reputation: 11237

It is often the case that an object declared automatic is allocated on the stack (which is relatively small), whereas an object declared static is allocated elsewhere.

Notice, this depends on your machine and on your compiler.

Upvotes: 2

Related Questions