Home > front end >  Why Does My Multidimensional Array Works Globally, but Not Scoped?
Why Does My Multidimensional Array Works Globally, but Not Scoped?

Time:04-15

I have a multidimensional array meant to represent 1024 * 1024 2-byte values. When I declare it in global scope, my fstream is able to read into it. When I declare it inside the same function that calls file.read, I get 0xC00000FD (stack overflow exception in windows?)

The following works, returning 0 when the program is finished

global md initialization

The following does not, exiting with 0xC00000FD

stack overflow exception

Eventually, I'd like to have the textureMap1 variable as part of a struct, but in my troubleshooting, I've found out that I can't seem to read into it, if it's not declared globally. I suspect it's something with static initialization, but I'm not familiar enough with C to know the nuances.

Why does the global declaration run without issue, but as soon as I move it into a scope, whether it be function scope or a struct, I get a stack overflow exception?

Edit

Link to Single File Header on pastebin.com

https://pastebin.com/raw/enLtebEe

To use in a project, you'll need a copy of a carnivores2 map file, as well as defining #STB_OCARN2_IMPLEMENTATION in one file, like stb headers.

CodePudding user response:

By default, programs built on Micrsoft Windows using the Microsoft compiler have a default maximum stack size of about 1 MB.

The declaration

unsigned short textureMap1[1024][1024];

allocates 2 MB on the stack, if you declare it as an automatic variable. That is why the stack overflows in your case.

If you instead declare the array as a global variable, then it won't be allocated on the stack, so it won't be a problem.

Stack space is a very limited resource, especially on Microsoft Windows (Linux has a larger default stack size of about 8 MB). Therefore, you should generally not allocate more than a few kilobytes on it, unless you know exactly what you are doing.

For allocating such large amounts of data, it is usually better to use dynamic memory allocation, such as new or std::make_unique, or use a container such as std::vector.

  • Related