C6262 warning and Visual Studio's stack size setting

(1) Problems encountered

The static array space is often related to the stack. I recently read the algorithm book. In order to improve efficiency, I often directly implement the algorithm in a static array. ). Then, there must be fewer good things, so the size of the default stack is limited. Most of the online sayings are that Linux defaults to 8MB, and Windows 2MB or 1MB. In fact, when we use static arrays, it will be smaller than this value, because there are other contents in the stack.

It happens that the machine has Visual Studio 2022, so I tried the definition of static arrays in different situations:

1 Release mode

In the Release mode of Visual Studio, arrays placed in functions or in the global area can exceed the above-mentioned limit. It seems that there is not a big limit on the size of the array, such as 4*64=256MB, and there is no prompt that exceeds a specific length.

#define MAX_SIZE 1024 * 1024 * 64
int a[MAX_SIZE];

2 Debug mode

There are two situations in Debug mode, one is that the array variable is declared globally, and the other is that the array variable is declared within the function.

(1) Static arrays are global variables

The size can exceed the limit of the default reserved stack size, and a larger storage space can be used. The test code is as follows:

#define MAX_SIZE 1024 * 1024 * 64
#include <stdio.h>

int a[MAX_SIZE];

int main()
{
  a[33554432] = 666;
  printf("%d\n", a[1024]);
  printf("%d\n", a[33554432]);
  return 0;
}

(2) The static array is a local variable in the function

When a static array is declared in a function, it will prompt that it exceeds the size of the reserved stack (the compiler specifies a stack space of 16384 bytes by default, which is 16KB), and it is recommended to use heap storage, such as a dynamic array:

警告  C6262  函数使用了堆栈的“268435456”个字节: 超过了 /analyze:stacksize '16384'。请考虑将某些数据移到堆中。

The test code is as follows:

void test_stack_overflow()
{
  int a[MAX_SIZE];
  a[33554432] = 666;
  printf("%d\n", a[1024]);
  printf("%d\n", a[33554432]);
}

The VS prompt is as follows:

 (2) Solutions

Modify the "Configuration Properties->Linker->System->Stack Reserve Size" option in the project properties to solve the problem of local array stack overflow as a static variable in debug mode.

This is to set the /STACK option in the linker, then change the reserved size of the stack, and the following two pictures can appear:

 

 (3) Summary

This is an article previously posted on my official account. It can be seen that the reserved stack size of VS is closely related to the linker option. When the linker is in /RELEASE mode, a large reserved stack space can be obtained (actually there are How much is yet to be verified), when the linker is in /DEBUG mode, there is a large limit on the reserved stack, which needs to be set in the linker option.

Guess you like

Origin blog.csdn.net/Humbunklung/article/details/125889907