Ошибка c6262 c

Цитата
Сообщение от Divergence
Посмотреть сообщение

А Вы можете разъяснить (или подсказать место, где это разъяснено) чем физически является этот стек и как оно работает? Я думал, что все грузится в оперативку, которой у всех сейчас стабильно больше 4 GB, соответственно у меня развязаны руки. А оказалось, что еще есть какой-то стек… Где он физически находится? Это КЭШ процессора?

При запуске процесса система выделяет в его адресном пространстве
специальную область под стек. В стеке хранятся локальные переменные,
адреса возвратов и прочая «сиюминутная» информация.

Например, когда вы в main размещаете массив int-ов из 100 элементов,
съедается, как минимум, «sizeof (int) * 100» байт стека. Когда вызывается
функция, адрес возврата размером «sizeof (ptr)» тоже сохраняется в стеке.
Чем больше вложенных вызовов и чем больше в каждой функции локальных
переменных, тем больше потребляется стековой памяти. Если пренебрегать
этим, можно нарваться на переполнение стека и тогда программа будет
аварийно завершена. Часто это происходит в алгоритмах с использованием
рекурсии или когда создаются стековые объекты большого размера.

Характерной особенностью стека является то, что он растет «вниз»,
от больших адресов к меньшим.

По умолчанию Windows резервирует под стек потока 1 мегабайт, причем
лишь часть этой памяти закоммичена, то есть, обеспечена реальными
физическими страницами памяти, остальное находится в состоянии «reserved».
При «поедании» стека система коммитит все новые и новые страницы для
него, пока не достигает конца области, которая изначально была
выделена под стек, и тогда наступает stack overflow…

For practice purposes, I tried creating a console app that will store basic information of employees and store it in a text file called employee-info.txt. I was able to write data in the text file but everytime the program writes new data, the C6262 warning appears. The warning can be seen in the function called employeeDataChecker() and employeeWriteData() under Employee.cpp, which I will indicate the codes below.

For employeeDataChecker(), the warning states that function uses ‘22800’ bytes of stack: exceeds/analyze:stacksize’16384′. Consider moving some data to heap. For employeeWriteData, it has the same warning but larger bytes of stack ‘23264’. I even tried adding pointers in the arrays I integrated in the code, but it mess up my code even more.

Kindly advice and some guidance on how to manage this or provide me with a better solution in achieving my goal. You can also pinpoint bad practices that I made, so that I can learn from it to improve my code. The code I provided below is long but I’m still working on it everyday to minimize the code.

Currently, this is the data stored in employee-info.txt:

       ID           Firstname            Lastname                 Sales
        1              Dwyane             Anthony             250000.00
        2              Joseph            Cardinal             450000.00
        4               Bruno                Mars             250000.00

This is the code for Employee.h:

#pragma once
#include<string>
#include<iostream>

class Employee
{
public:
struct EmployeeRecord {
    static const int recordSize = 100;
    static const int fieldSize = 4;
    std::string record[recordSize][fieldSize];
};

public:
Employee();
~Employee();
void employeeDataChecker();
void employeeWriteData(int recordCount, std::string recordCopy[EmployeeRecord::recordSize][EmployeeRecord::fieldSize]);
void employeeDisplayData();
EmployeeRecord& employeeReturnRecordArray();

private:
EmployeeRecord emp_record;

};

And here is the code in Employee.cpp:

void Employee::employeeDataChecker() {
//Check if there are data in the employee-info.txt
EmployeeRecord emp;
std::ifstream inFile, inFile2;
int recordCount = 0;
inFile.open("C:\\Users\\RJ\\Desktop\\employee-info.txt"); // use to get the number of values stored in record array
inFile2.open("C:\\Users\\RJ\\Desktop\\employee-info.txt"); // use to get all contents in record array

for (int index = 0; index < emp.recordSize; index++) {
    for (int index2 = 0; index2 < emp.fieldSize; index2++) {
        while (inFile >> emp.record[index][index2]) {
            recordCount++;
        }
    }
}

for (int index = 0; index < emp.recordSize; index++) {
    for (int index2 = 0; index2 < emp.fieldSize; index2++) {
        inFile2 >> emp.record[index][index2];
    }
}
//used as a dummy array to hold the values in record array and pass as an argument 
std::string recordCopy[emp.recordSize][emp.fieldSize];


    for (int index = 0; index < emp.recordSize; index++) {
        for (int index2 = 0; index2 < emp.fieldSize; index2++) {
            recordCopy[index][index2] = emp.record[index][index2];
        }
    }



inFile.close();
inFile2.close();

employeeWriteData(recordCount, recordCopy);
}//end of employeeDataChecker

void Employee::employeeWriteData(int recordCount, std::string recordCopy[EmployeeRecord::recordSize][EmployeeRecord::fieldSize]) {
Employee emp;
EmployeeRecord empRec;
int numEmployees;
std::string firstName, lastName;
std::string fullName = "";
double sales;

std::ofstream outFile;
outFile.open("C:\\Users\\RJ\\Desktop\\employee-info.txt", std::ofstream::app);

//pass all values from recordCopy to record array
for (int index = 0; index < empRec.recordSize; index++) {
    for (int index2 = 0; index2 < empRec.fieldSize; index2++) {
        empRec.record[index][index2] = recordCopy[index][index2];
    }
}

std::cout << "------------------------------------------------" << std::endl;
std::cout << "Enter The Number of Employees to Add: ";
std::cin >> numEmployees;
std::cin.get();

if (recordCount == 0) {

    //If employee-info.txt is empty.
    outFile << std::fixed << std::showpoint << std::setprecision(2);
    outFile << std::setw(5) << "ID";
    outFile << std::setw(20) << "Firstname";
    outFile << std::setw(20) << "Lastname";
    outFile << std::setw(22) << "Sales" << std::endl;

    for (int index = 0; index < numEmployees; index++) {
        int empID = index;
        empID++;
        std::cout << "*****Employee ID No." << empID << "*****" << std::endl;
        std::cout << "Enter First Name: ";
        std::getline(std::cin, firstName);
        std::cout << "Enter Last Name: ";
        std::getline(std::cin, lastName);
        fullName = firstName + " " + lastName;

        std::cout << "Enter Total Sales: ";
        std::cin >> sales;

        std::string empIDConverted = std::to_string(empID);
        std::string salesConverted = std::to_string(sales);

        for (int index2 = 0; index2 < empRec.fieldSize; index2++) {
            if (index2 == 0) {
                empRec.record[index][index2] = empIDConverted;
            }
            else if (index2 == 1) {
                empRec.record[index][index2] = firstName;
            }
            else if (index2 == 2) {
                empRec.record[index][index2] = lastName;
            }
            else if (index2 == 3) {
                empRec.record[index][index2] = salesConverted;
            }
        }

        outFile << std::fixed << std::showpoint << std::setprecision(2);
        int numSetW;
        for (int index2 = 0; index2 < empRec.fieldSize; index2++) {

            if (index2 == 0) {
                numSetW = 5;
            }
            else if(index2 == 3){
                numSetW = 22;
            }
            else {
                numSetW = 20;
            }

            if (index2 == (empRec.fieldSize - 1)) {

                std::string getSales = empRec.record[index][index2];
                double salesPreviousType;
                std::istringstream iss(getSales);
                iss >> salesPreviousType;

                outFile << std::setw(numSetW) << salesPreviousType << std::endl;
            }
            else {
                outFile << std::setw(numSetW) << empRec.record[index][index2];
            }
        }
        std::cin.get();
    }

}
else if (recordCount >= empRec.fieldSize) {
    //If employee-info.txt already has an existing data. It will write new data at the end of record array.

    int rows = recordCount / empRec.fieldSize;
    int increasedFieldSize = empRec.fieldSize * 2;
    int preIndex = rows;

    for (int index = rows; index < (numEmployees + preIndex); index++) {
        int empID = index;
        empID++;
        std::cout << "*****Employee ID No." << empID << "*****" << std::endl;
        std::cout << "Enter First Name: ";
        std::getline(std::cin, firstName);
        std::cout << "Enter Last Name: ";
        std::getline(std::cin, lastName);
        fullName = firstName + " " + lastName;

        std::cout << "Enter Total Sales: ";
        std::cin >> sales;

        std::string empIDConverted = std::to_string(empID);
        std::string salesConverted = std::to_string(sales);

        for (int index2 = 0; index2 < empRec.fieldSize; index2++) {
            if (index2 == 0) {
                empRec.record[index][index2] = empIDConverted;
            }
            else if (index2 == 1) {
                empRec.record[index][index2] = firstName;
            }
            else if (index2 == 2) {
                empRec.record[index][index2] = lastName;
            }
            else if (index2 == 3) {
                empRec.record[index][index2] = salesConverted;
            }
        }

        outFile << std::fixed << std::showpoint << std::setprecision(2);
        int numSetW;
        for (int index2 = 0; index2 < empRec.fieldSize; index2++) {

            if (index2 == 0) {
                numSetW = 5;
            }
            else if (index2 == 3) {
                numSetW = 22;
            }
            else {
                numSetW = 20;
            }

            if (index2 == (empRec.fieldSize - 1)) {

                std::string getSales = empRec.record[index][index2];
                double salesPreviousType;
                std::istringstream iss(getSales);
                iss >> salesPreviousType;

                outFile << std::setw(numSetW) << salesPreviousType << std::endl;
            }
            else {
                outFile << std::setw(numSetW) << empRec.record[index][index2];
            }

        }
        std::cin.get();
    }

}
else {
    std::cout << "Number problem!";
}


outFile.close();
  }//end of employeeWriteData

я использую 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

I’m trying to learn C++ by making a password generator, and when I was almost done, I had a warning (Warning C6262 Function uses ‘20044’ bytes of stack: exceeds /analyze:stacksize ‘16384’. Consider moving some data to heap.)
And since I’m a beginner at C++ and only now the basics, I don’t know what to do.

Since I had 2 arrays in the function, I’ve tried to move them out of the main function, It did lower the number of bytes it was using (20100), it was still too high. I’ve tried to read Microsoft’s errors guide, but I don’t know about heaps or moving said data to the heaps in C++

Here’s the code:

#include <iostream>
#include <random>
using namespace std;

class Randomer {
    // random seed by default
    std::mt19937 gen_;
    std::uniform_int_distribution<size_t> dist_;

public:
    /*  ... some convenient ctors ... */

    Randomer(size_t min, size_t max, unsigned int seed = std::random_device{}())
        : gen_{ seed }, dist_{ min, max } {
    }

    // if you want predictable numbers
    void SetSeed(unsigned int seed) {
        gen_.seed(seed);
    }

    size_t operator()() {
        return dist_(gen_);
    }
};

string alphabet{ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
                          'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
                          'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
                          'k', 'l', 'm', 'n','o','p', 'q', 'r', 's', 't', 'u', 'v',
                          'w', 'x', 'y', 'z' };
string specialchars{ ' ','!','#','$', '%', '&','(',')','*','+','-','.','/',':',';','<','=','>','?','@' };
Randomer rand1{ 0,2 };
Randomer randint{ 0,9 };
Randomer randalpha{ 0,26 };
Randomer randspecial{ 0,20 };
int main()
{
    while (true) { //This loop is to restart the program if an invaild response is detected.
        int i;
        int lengthofpassword = 8;

        cout << "Do you want to generate a password or to type in a existing password to make it stronger?\n\n(1 for generation, 2 for existing password)\n";
        cin >> i;
        int g = 0;
        if (i == 1) {
            cout << "\nWhat is the length of the password?\n";
            cin >> lengthofpassword;
            while (g <= lengthofpassword -1) {

                //if (rand() == 0) {//numb
                //  cout << randint();
                //}
                //else if (rand() == 1) {//letter
                //  cout << alphabet[randalpha()];
                //}
                switch (rand1())
                {
                case 0:
                    cout << alphabet[randalpha()];
                    break;
                case 1:
                    cout << randint();
                    break;
                case 2:
                    cout << specialchars[randspecial()];
                    break;
                default:
                    break;
                }

                g = g + 1;
                //cout << "\n\n" << g << "\n\n";
            }
            cout << "\n";
            system("pause");
            return 0;

        }
        else if (i == 2) {
            cout << "\n";
            system("pause");
            return 0;
        }
        else {
            cout << "\n";
            cout << "Invaild Response!\n";
        }
    }
//  system("pause");
    return 0;
}

Trying to condense it for stackoverflow didn’t work.
Although it hasn’t broken yet and works as expected, I feel like I should learn this type of stuff now rather than later.

Цитата
Сообщение от 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

EXCESSIVESTACKUSAGE

__WARNING_EXCESSIVESTACKUSAGE

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

  1. In the Visual Studio IDE, select the project in the Solution Explorer window.

  2. On the menu bar, choose Project > Properties.

  3. In the Property Pages dialog box, select the Configuration Properties > C/C++ > Command Line property page.

  4. 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;
}

Jonathan Leffler's user avatar

asked Oct 21, 2020 at 3:34

Aaron Macasaet's user avatar

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

Dylan Gentile's user avatar

3

Понравилась статья? Поделить с друзьями:
  • Ошибка cash manager windows 10
  • Ошибка case 1059
  • Ошибка casappa обрыв пропорционального клапана лиаз
  • Ошибка cas запуск двигателя при работающем стартере
  • Ошибка card expired