Сообщение от Divergence
А Вы можете разъяснить (или подсказать место, где это разъяснено) чем физически является этот стек и как оно работает? Я думал, что все грузится в оперативку, которой у всех сейчас стабильно больше 4 GB, соответственно у меня развязаны руки. А оказалось, что еще есть какой-то стек… Где он физически находится? Это КЭШ процессора?
При запуске процесса система выделяет в его адресном пространстве
специальную область под стек. В стеке хранятся локальные переменные,
адреса возвратов и прочая «сиюминутная» информация.
Например, когда вы в main размещаете массив int-ов из 100 элементов,
съедается, как минимум, «sizeof (int) * 100» байт стека. Когда вызывается
функция, адрес возврата размером «sizeof (ptr)» тоже сохраняется в стеке.
Чем больше вложенных вызовов и чем больше в каждой функции локальных
переменных, тем больше потребляется стековой памяти. Если пренебрегать
этим, можно нарваться на переполнение стека и тогда программа будет
аварийно завершена. Часто это происходит в алгоритмах с использованием
рекурсии или когда создаются стековые объекты большого размера.
Характерной особенностью стека является то, что он растет «вниз»,
от больших адресов к меньшим.
По умолчанию Windows резервирует под стек потока 1 мегабайт, причем
лишь часть этой памяти закоммичена, то есть, обеспечена реальными
физическими страницами памяти, остальное находится в состоянии «reserved».
При «поедании» стека система коммитит все новые и новые страницы для
него, пока не достигает конца области, которая изначально была
выделена под стек, и тогда наступает stack overflow…
When I build the code, this run without problems, however I debuging the code, this generate the message: Function uses ‘1600000620’ bytes of stack: exceeds/analyze:stacksize 16384′.
I put the declaration: int array[2000][2000] into int main{} because when int array[2000][2000] was out of int main{}, it generate the error: array is ambiguous.
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
/* Function to sort an array using insertion sort*/
void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++){
key = arr[i];
j = i - 1;
/* Move elements of arr[0..i-1], that aregreater than key, to one
position aheadof their current position */
while (j >= 0 && arr[j] > key){
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
int arr[2000][2000];
int main()
{
int array[2000][2000];
int window[9], row = 0, col = 0, numrows = 0, numcols = 0, MAX = 0;
ifstream infile("phone.jpg");
stringstream ss;
string inputLine = "";
// First line : version
getline(infile, inputLine);
if (inputLine.compare("P2") != 0) cerr << "Version error" << endl;
else cout << "Version : " << inputLine << endl;
// Continue with a stringstream
ss << infile.rdbuf();
// Secondline : size of image
ss >> numcols >> numrows >> MAX;
//print total number of rows, columns and maximum intensity of image
cout << numcols << " columns and " << numrows << " rows" << endl<<
"Maximium Intesity "<< MAX <<endl;
//Initialize a new array of same size of image with 0
for (row = 0; row <= numrows; ++row)
{
array[row][0] = 0;
}
for (col = 0; col <= numcols; ++col) {
array[0][col] = 0;
}
// Following lines : data
for (row = 1; row <= numrows; ++row)
{
for (col = 1; col <= numcols; ++col)
{
//original data store in new array
ss >> array[row][col];
}
}
// Now print the array to see the result
for (row = 1; row <= numrows; ++row)
{
for (col = 1; col <= numcols; ++col)
{
//neighbor pixel values are stored in window including this pixel
window[0] = array[row - 1][col - 1];
window[1] = array[row - 1][col];
window[2] = array[row - 1][col + 1];
window[3] = array[row][col - 1];
window[4] = array[row][col];
window[5] = array[row][col + 1];
window[6] = array[row + 1][col - 1];
window[7] = array[row + 1][col];
window[8] = array[row + 1][col + 1];
//sort window array
insertionSort(window, 9);
//put the median to the new array
arr[row][col] = window[4];
}
}
ofstream outfile;
//new file open to stroe the output image
outfile.open("Medianfilter.pnm");
outfile << "P2" << endl;
outfile << numcols << " " << numrows << endl;
outfile << "255" << endl;
for (row = 1; row <= numrows; ++row)
{
for (col = 1; col <= numcols; ++col)
{
//store resultant pixel values to the output file
outfile << arr[row][col] << " ";
}
}
outfile.close();
infile.close();
return 0;
}
I expected that this program clear a image, take out noise from images.
я использую Visual Studio 2010
с Code Analysis
активируется. В моем коде есть строка, выделяющая некоторую память в функции:
TCHAR someString[40000];
Анализ кода выдает предупреждение:
предупреждение C6262: функция использует «40000» байтов стека: превышает / анализирует: размер стека «16384». Рассмотрите возможность перемещения некоторых данных в кучу
Интересно, должен ли я принять предупреждение серьезно? Должен ли я столкнуться с какими-то реальными проблемами, если я выделю некоторую память в стеке> 16384? Или это просто общее предупреждающее сообщение, которое напоминает мне, что я должен заботиться о размере своего стека в целом? Насколько я знаю, размер стека по умолчанию составляет 1 МБ (если вы используете Visual Studio).
8
Решение
Следует признать, что это сообщение может сбивать с толку, поскольку VS (свойства проекта) действительно сообщает, что по умолчанию установлено значение 1M. Однако, если вы посмотрите на текст предупреждение, Вы заметите, что на самом деле ограничение для анализа кода составляет 16 КБ. Следуйте инструкциям внизу этой ссылки, чтобы исправить предупреждение.
6
Другие решения
Я обнаружил, что к таким предупреждениям следует относиться серьезно.
У меня была декларация
{ // some local branch deep inside a function char T[2000000]; ... }
оставил по ошибке где-то глубоко внутри большой функции. Функция всегда вылетала сразу после входа в функцию, даже если объявление в локальной ветке было далеко, и я так и не попал туда с отладчиком.
Это было трудно найти в MS Visual Studio, даже когда анализ кода дал мне предупреждение.
1
title | description | ms.date | f1_keywords | helpviewer_keywords | |||
---|---|---|---|---|---|---|---|
Warning C6262 |
Visual Studio C++ Code Analysis warning C6262 description and resolution. |
10/14/2020 |
|
C6262 |
Warning C6262
Function uses constant_1 bytes of stack: exceeds /analyze:stacksize constant_2. Consider moving some data to heap
Remarks
This warning indicates that stack usage that exceeds a preset threshold (constant_2) has been detected in a function. The default stack frame size for this warning is 16 KB for user mode, 1 KB for kernel mode. Stack—even in user mode—is limited, and failure to commit a page of stack causes a stack overflow exception. Kernel mode has a 12 KB stack size limit, which can’t be increased. Try to aggressively limit stack use in kernel-mode code.
To correct the problem behind this warning, you can either move some data to the heap or to other dynamic memory. In user mode, one large stack frame may not be a problem—and this warning may be suppressed—but a large stack frame increases the risk of a stack overflow. (A large stack frame might occur if the function uses the stack heavily or is recursive.) The total stack size in user mode can be increased if stack overflow actually occurs, but only up to the system limit.
For kernel-mode code—for example, in driver projects—the value of constant_2 is set to 1 KB. Well-written drivers should have few functions that approach this value, and changing the limit downward may be desirable. The same general techniques that are used for user-mode code to reduce the stack size can be adapted to kernel-mode code.
Code analysis name: EXCESSIVESTACKUSAGE
Adjust the stack size to suppress the warning
You can use the /analyze:stacksize
command-line option to change the value for constant_2, but increasing it introduces a risk that an error may not be reported.
To suppress the warning on the command line
- Add the
/analyze:stacksize <new-size>
option to the compiler command line. Use a value for<new-size>
that’s larger than constant_1. For example, if constant_1 is 27180, you might enter/analyze:stacksize 32768
.
To suppress the warning in the IDE
-
In the Visual Studio IDE, select the project in the Solution Explorer window.
-
On the menu bar, choose Project > Properties.
-
In the Property Pages dialog box, select the Configuration Properties > C/C++ > Command Line property page.
-
In Additional options, add
/analyze:stacksize <new-size>
, where<new-size>
is larger than constant_1. For example, if constant_1 is 27180, you might enter/analyze:stacksize 32768
. Choose OK to save your changes.
Example
The following code generates this warning because char buffer
requires 16,382 bytes on the stack, and the local integer variable i
requires another 4 bytes, which together exceed the default stack size limit of 16 KB.
// cl.exe /c /analyze /EHsc /W4 #include <windows.h> #define MAX_SIZE 16382 void f( ) { int i; char buffer[MAX_SIZE]; i = 0; buffer[0]=''; // code... }
The following code corrects this warning by moving some data to heap.
// cl.exe /c /analyze /EHsc /W4 #include <stdlib.h> #include <malloc.h> #define MAX_SIZE 16382 void f( ) { int i; char *buffer; i = 0; buffer = (char *) malloc( MAX_SIZE ); if (buffer != NULL) { buffer[0] = ''; // code... free(buffer); } }
The use of malloc
and free
has many pitfalls, such as memory leaks and exceptions. To avoid these kinds of leaks and exception problems altogether, use the mechanisms that are provided by the C++ Standard Library (STL). These include shared_ptr
, unique_ptr
, and vector
. For more information, see Smart Pointers and C++ Standard Library.
See also
/STACK
(Stack allocations)
_resetstkoflw
How to: Use native run-time checks
This code C6262 warning keeps showing up causing problems to the program and I tried searching for possible solutions but I am having a difficult time understanding. I would really appreciate if some could help me with this and if you could point out any bad parts of the code that I could improve.
#include <iostream>
#include <cstdlib>
#include <algorithm>
using namespace std;
class sorting {
private:
int size, elements;
int arr[5000], x;
public:
void sort() {
cout << "Enter number of desired elements for the 1st set" << ">"; cin >> elements;
arr[elements];
half(); cout << endl;
bubble();
for (int i = 0; i < elements; i++) {
cout << arr[i] << " ";
}
}
void half() {
for (int i = 0; i < elements / 2; i++) {
arr[i] = i + 1;
}
for (int i = elements / 2; i < elements; i++) {
arr[i] = rand();
}
cout << "This is the elements of the 1st set: ";
for (int i = 0; i < elements; i++) {
cout << arr[i] << " ";
}
}
void random() {
for (int i = 0; i < elements; i++) {
arr[i] = i + 1;
}
random_shuffle(&arr[0], &arr[elements]);
cout << "This is the elements of the 2nd set: ";
for (int i = 0; i < elements; i++) {
cout << arr[i] << " ";
}
}
void ascend_descend() {
int x = elements / 2;
arr[0] = x;
for (int i = 0; i < elements / 2; i++) {
arr[i + 1] = x - 1;
x--;
}
for (int i = elements / 2; i < elements; i++) {
arr[i] = i + 1;
}
cout << "This is the elements of the 3rd set: ";
for (int i = 0; i < elements; i++) {
cout << arr[i] << " ";
}
};
void bubble() {
for (int i = 0; i < elements; i++) {
int temp;
for (int j = i + 1; j < elements; i++) {
if (arr[j] < arr[i]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
};
}
};
int main()
{
sorting sortObject;
sortObject.sort();
return 0;
}
asked Oct 21, 2020 at 3:34
3
Right at the top of the class declaration you have int arr[5000], x;
That will allocate the array of ints on the stack. Your compiler is warning you that that array might not fit on the stack, and you should allocate it on the heap instead. For an explanation of stack vs heap see this. Assuming you still want to use a c-style array with pointers (see my second solution for what would be more idiomatic), you would allocate the array in the constructor, and free it in the destructor.
class sorting
{
int size;
int elements;
int* arr;
int x;
public:
sorting()
{
arr = new int[5000];
}
~sorting()
{
delete arr;
}
/*the rest of your code...*/
};
This solution takes more of a manual memory management style, and unless you have a good reason for doing so, I would recommend using std::vector instead of manually allocating your array. This will keep track of the elements and size. So your member variables will look like this instead:
class sorting
{
private:
int x;
int elements;
vector<int> arr;
}
Then you can use arr.push_back(int)
to add elements the vector. arr[i]
to access and set them, and arr.size()
to get how many elements are in your array.
answered Oct 21, 2020 at 3:54
3