Меню

Ошибка stack around the variable

I have a program which prompts me the error in VS2010, in debug :

Error: Stack around the variable 'x' was corrupted

This gives me the function where a stack overflow likely occurs, but I can’t visually see where the problem is.

Is there a general way to debug this error with VS2010? Would it be possible to indentify which write operation is overwritting the incorrect stack memory?
thanks

asked Oct 30, 2012 at 15:32

lezebulon's user avatar

6

Is there a general way to debug this error with VS2010?

No, there isn’t. What you have done is to somehow invoke undefined behavior. The reason these behaviors are undefined is that the general case is very hard to detect/diagnose. Sometimes it is provably impossible to do so.

There are however, a somewhat smallish number of things that typically cause your problem:

  • Improper handling of memory:
    • Deleting something twice,
    • Using the wrong type of deletion (free for something allocated with new, etc.),
    • Accessing something after it’s memory has been deleted.
  • Returning a pointer or reference to a local.
  • Reading or writing past the end of an array.

answered Oct 30, 2012 at 16:08

David Hammen's user avatar

David HammenDavid Hammen

32k8 gold badges59 silver badges107 bronze badges

This can be caused by several issues, that are generally hard to see:

  • double deletes
  • delete a variable allocated with new[] or delete[] a variable allocated with new
  • delete something allocated with malloc
  • delete an automatic storage variable
  • returning a local by reference

If it’s not immediately clear, I’d get my hands on a memory debugger (I can think of Rational Purify for windows).

answered Oct 30, 2012 at 15:34

Luchian Grigore's user avatar

Luchian GrigoreLuchian Grigore

250k63 gold badges454 silver badges619 bronze badges

6

This message can also be due to an array bounds violation. Make sure that your function (and every function it calls, especially member functions for stack-based objects) is obeying the bounds of any arrays that may be used.

answered Oct 30, 2012 at 15:35

Omaha's user avatar

OmahaOmaha

2,26214 silver badges18 bronze badges

Actually what you see is quite informative, you should check in near x variable location for any activity that might cause this error.

Below is how you can reproduce such exception:

int main() {
    char buffer1[10];
    char buffer2[20];
    memset(buffer1, 0, sizeof(buffer1) + 1);
    return 0;
}

will generate (VS2010):

Run-Time Check Failure #2 — Stack around the variable ‘buffer1’ was corrupted.

obviously memset has written 1 char more than it should. VS with option GS allows to detect such buffer overflows (which you have enabled), for more on that read here: http://msdn.microsoft.com/en-us/library/Aa290051.

You can for example use debuger and step throught you code, each time watch at contents of your variable, how they change. You can also try luck with data breakpoints, you set breakpoint when some memory location changes and debugger stops at that moment,possibly showing you callstack where problem is located. But this actually might not work with GS flag.

For detecting heap overflows you can use gflags tool.

answered Oct 30, 2012 at 16:32

marcinj's user avatar

marcinjmarcinj

47.5k9 gold badges79 silver badges97 bronze badges

I was puzzled by this error for hours, I know the possible causes, and they are already mentioned in the previous answers, but I don’t allocate memory, don’t access array elements, don’t return pointers to local variables…

Then finally found the source of the problem:

*x++;

The intent was to increment the pointed value. But due to the precedence ++ comes first, moving the x pointer forward then * does nothing, then writing to *x will be corrupt the stack canary if the parameter comes from the stack, making VS complain.

Changing it to (*x)++ solves the problem.

Hope this helps.

answered Jan 7, 2014 at 13:31

Calmarius's user avatar

CalmariusCalmarius

18k18 gold badges106 silver badges151 bronze badges

Here is what I do in this situation:

Set a breakpoint at a location where you can see the (correct) value of the variable in question, but before the error happens. You will need the memory address of the variable whose stack is being corrupted. Sometimes I have to add a line of code in order for the debugger to give me the address easily (int *x = &y)

At this point you can set a memory breakpoint (Debug->New Breakpoint->New Data Breakpoint)

Hit Play and the debugger should stop when the memory is written to. Look up the stack (mine usually breaks in some assembly code) to see whats being called.

answered Oct 30, 2012 at 16:04

Ben's user avatar

BenBen

1,21720 silver badges24 bronze badges

I usually follow the variable before the complaining variable which usually helps me get the problem. But this can sometime be very complex with no clue as you have seen it. You could enable Debug menu >> Exceptions and tick the ‘Win32 exceptions» to catch all exceptions. This will still not catch this exceptions but it could catch something else which could indirectly point to the problem.

In my case it was caused by library I was using. It turnout the header file I was including in my project didn’t quite match the actual header file in that library (by one line).

There is a different error which is also related:

0xC015000F: The activation context being deactivated is not the most
recently activated one.

When I got tired of getting the mysterious stack corrupted message on my computer with no debugging information, I tried my project on another computer and it was giving me the above message instead. With the new exception I was able to work my way out.

answered Jun 16, 2014 at 15:48

zar's user avatar

zarzar

10.9k13 gold badges90 silver badges171 bronze badges

I encountered this when I made a pointer array of 13 items, then trying to set the 14th item. Changing the array to 14 items solved the problem. Hope this helps some people ^_^

answered Oct 9, 2015 at 5:50

Kyle Alexander Buan's user avatar

One relatively common source of «Stack around the variable ‘x’ was corrupted» problem is wrong casting. It is sometimes hard to spot. Here is an example of a function where such problem occurs and the fix. In the function assignValue I want to assign some value to a variable. The variable is located at the memory address passed as argument to the function:

using namespace std;
            
template<typename T>
void assignValue(uint64_t address, T value)
{
    int8_t* begin_object = reinterpret_cast<int8_t*>(std::addressof(value));
    // wrongly casted to (int*), produces the error (sizeof(int) == 4)
    //std::copy(begin_object, begin_object + sizeof(T), (int*)address);  
    // correct cast to (int8_t*), assignment byte by byte, (sizeof(int8_t) == 1)
    std::copy(begin_object, begin_object + sizeof(T), (int8_t*)address); 
}
        
int main()
{
    int x = 1;
    int x2 = 22;
    assignValue<int>((uint64_t)&x, x2);
    assert(x == x2);
}

answered Feb 1, 2021 at 9:36

Andrushenko Alexander's user avatar

void GameBoard::enterShips()
{
    char location[1];
    int ships = 0;
    int count = 1;

    while(ships < NUM_SHIPS)
    {
        cout << "Enter a location for Ship " << count << ": ";
        cin >> location;
        cout << endl;

        Grid[location[0]][location[1]] = SHIP;
        ships++;
        count++;
    }
}

Im writing a battleship game. I have the board layouts working and the computers randomly generated ships. Now I am working on this method to prompt the user to enter coordinates for the ships When I run the program, it allows me to enter 5 ships. When I enter the 6th ship, it gives me this error.

Stack around the variable location was corrupted.

Ive looked for answers online and have not found anything exclusive.

Any help would be appreciated.

SoapBox's user avatar

SoapBox

20.4k3 gold badges51 silver badges86 bronze badges

asked Feb 27, 2011 at 20:57

bluetickk's user avatar

1

location is an array of a single char.
There is no location[1].

answered Feb 27, 2011 at 21:00

SLaks's user avatar

SLaksSLaks

856k175 gold badges1885 silver badges1953 bronze badges

You are prompting the memory address of location array to your user. You should ask location indices separately:

void GameBoard::enterShips()
{
    int location[2];
    int ships = 0;
    int count = 1;

    while(ships < NUM_SHIPS)
    {
        cout << "Enter a location for Ship " << count << ": ";
        cin >> location[0];
        cin >> location[1];
        cout << endl;

        Grid[location[0]][location[1]] = SHIP;
        ships++;
        count++;
    }
}

Notice int location[2]; since an array of size 1 can only hold one element. I also changed the element type to int. Reading char’s from the console will result in ASCII values, which are probably not what you want.

answered Feb 27, 2011 at 21:02

Tugrul Ates's user avatar

Tugrul AtesTugrul Ates

9,1981 gold badge32 silver badges58 bronze badges

1

cin >> location;

location is an array of one char. This can’t succeed because when you read from a stream into a char array, a null terminator has to be added (which takes one character). You will inevitably overrun the bounds of the array.

You can use a std::string, which will help you avoid any buffer overrun issues:

std::string location;
if (!(std::cin >> location)) {
    // handle input error
}

Note also that you probably need to convert the string representations of the numbers into numeric values. You can easily do this by reading from the stream into two int objects instead:

int x_location, y_location;
if (!(std::cin >> x_location >> y_location)) { 
    // Handle input error
}

if (x_location >= X_DIMENSION || x_location < 0 ||
    y_location >= Y_DIMENSION || y_location < 0) {
    // Handle out-of-range error 
}

// use x_location and y_location

answered Feb 27, 2011 at 21:04

James McNellis's user avatar

James McNellisJames McNellis

344k75 gold badges906 silver badges974 bronze badges

You made the location variable only able to hold a single character. You access it expecting it to hold at least 2 characters. If you’re using cin and expecting to read exactly two characters, a better method would be:

char locationX, locationY;
// ...
std::cin >> locationX >> locationY;
// ...
Grid[locationX][locationY] = SHIP;

answered Feb 27, 2011 at 21:01

SoapBox's user avatar

SoapBoxSoapBox

20.4k3 gold badges51 silver badges86 bronze badges

valeriy007

81 / 25 / 19

Регистрация: 27.10.2014

Сообщений: 420

1

10.07.2015, 17:51. Показов 13297. Ответов 24

Метки нет (Все метки)


Учусь создавать списки. Идея такова чтобы создать список в отдельном cpp, а пользователь имел доступ только к функциям добавления, удаления и т.д. Все было хорошо, но вот столкнулся с проблемой после завершения программы всегда пишет:
Run-Time Check Failure #2 — Stack around the variable ‘a’ was corrupted.

Кликните здесь для просмотра всего текста

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
struct Rab
{   
    char *name; 
};
 
struct List{
private:
    Rab elem;
    List *next;
    List *begin = NULL;
    List *end = NULL;
public:
 
    void add(char *x)
    {
        List *add = new List;
        add->elem.name = x;
        add->next = NULL;
        if (!begin)
            begin = add;
        else
            end->next = add;
        end = add;
    }
 
    void print()
    {
        while (begin)
        {
            std::cout << begin->elem.name << std::endl;
            begin = begin->next;
        }
    }
};

Кликните здесь для просмотра всего текста

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
int main()
{
    char a[] = "";
    std::cin >> a;
 
    List myList;
    myList.add(a);
    std::cout << "nnn";
    myList.print();
 
    system("pause");
    return 0;
}

Если не трудно гляньте, может еще ошибок понаделал.

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



IrineK

Заблокирован

10.07.2015, 18:23

2

Не выделяете памяти под строки: ни в main, ни в add



0



valeriy007

81 / 25 / 19

Регистрация: 27.10.2014

Сообщений: 420

10.07.2015, 18:31

 [ТС]

3

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

Не выделяете памяти под строки: ни в main, ни в add

C++
1
2
char *a = new char[];
    std::cin >> a;

Так будет правильно? В add думаю не надо, ведь в функцию передаю только адрес.



0



858 / 447 / 112

Регистрация: 06.07.2013

Сообщений: 1,495

10.07.2015, 18:44

4

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

char *a = new char[];

в квадратных скобках нужно указать под сколько букв нужно выделить память



0



81 / 25 / 19

Регистрация: 27.10.2014

Сообщений: 420

10.07.2015, 18:52

 [ТС]

5

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

в квадратных скобках нужно указать под сколько букв нужно выделить память

просто хотелось бы вводить без ограничений, то есть сколько ввел, столько и вывел…
Можно сказать я не знаю сколько пользователь введет в строку букв…



0



IrineK

Заблокирован

10.07.2015, 19:26

6

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

Можно сказать я не знаю сколько пользователь введет в строку букв…

Вот это

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

C++
1
char a[] = "";

означает, что выделен 1 байт памяти: на конец строки.
Пользователю развернуться негде.

Сделайте нормальный буфер. Скажем

C++
1
char a[BUFSIZ];

Вот это

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

std::cin >> a;

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

Добавлено через 9 минут

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

В add думаю не надо, ведь в функцию передаю только адрес

Адрес чего? И где оно лежит? И где лежать будет?



0



valeriy007

81 / 25 / 19

Регистрация: 27.10.2014

Сообщений: 420

10.07.2015, 22:17

 [ТС]

7

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

Пользователю развернуться негде.

А если так?

C++
1
2
char *a = new char[];
    std::cin >> a;

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

Адрес чего? И где оно лежит? И где лежать будет?

Адрес «а» по которому элемент добавляется в список.



0



IrineK

Заблокирован

10.07.2015, 23:04

8

В рамках данного кода

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
 
struct Rab
{
    char *name;
};
 
struct List
{
private:
    Rab elem;
    List *next;
    List *begin = NULL;
    List *end = NULL;
public:
 
    void add(char *x)
    {
        List *add = new List;
        add->elem.name = new char[strlen(x) + 1];
        strcpy(add->elem.name, x);
        add->next = NULL;
        if (!begin)
            begin = add;
        else
            end->next = add;
        end = add;
    }
 
    void print()
    {
        while (begin)
        {
            std::cout << begin->elem.name << std::endl;
            begin = begin->next;
        }
    }
};
 
 
int main()
{
    char a[BUFSIZ];
    List myList;
 
    while (std::fgets(a, BUFSIZ, stdin) && a[0] != 'n')
    {
        if (a[strlen(a) - 1] == 'n')
            a[strlen(a) - 1] = '';
        
        myList.add(a);
    }
    
    myList.print();
 
    getchar();
    return 0;
}

Чтобы закончить ввод, введите пустую строку.

Ну, и нужно написать очистку памяти.



0



valeriy007

81 / 25 / 19

Регистрация: 27.10.2014

Сообщений: 420

11.07.2015, 14:38

 [ТС]

9

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

C++
1
2
3
4
5
6
7
while (std::fgets(a, BUFSIZ, stdin) && a[0] != 'n') 
{ 
if (a[strlen(a) - 1] == 'n') 
a[strlen(a) - 1] = '';
 
 myList.add(a); 
}

Это как я понял для правильно ввода в консоли. Просто я список делаю не под консоль, а чтоб потом можно было удобно воспользоваться в полноценной программе.

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

Ну, и нужно написать очистку памяти.

Очистку памяти от всего списка?

Объясните немного про BUFSIZ… Вместо него можно просто написать 512?. В нете почитал, он используется в основном при работе с файлами…

Добавлено через 1 час 16 минут

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

C++
1
2
add->elem.name = new char[strlen(x) + 1];
strcpy(add->elem.name, x);

Тут сложилась такая ситуация:
Ошибка 2 error C4996: ‘strcpy’: This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. c:usersuserdocumentsvisual studio 2013projectstrenlistlist.hpp
Воспользовался тем что мне предложил студио, функция принимает 3 параметра, куда, сколько выделить байт(как я понял) и откуда. Я правильно воспользовался ею?)

C++
1
2
add->elem.name = new char [strlen(x) + 1];
strcpy_s(add->elem.name, strlen(x) + 1, x);



0



IrineK

Заблокирован

11.07.2015, 15:50

10

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

Я правильно воспользовался ею?)

Вы еще и в студии?
Тогда на самом верху, самой первой строкой

C++
1
#define _CRT_SECURE_NO_WARNINGS

И ничего вот этого с _s не пишите. Ну его.

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

в полноценной программе.

Там будет кириллица?



0



81 / 25 / 19

Регистрация: 27.10.2014

Сообщений: 420

11.07.2015, 15:58

 [ТС]

11

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

Там будет кириллица?

да

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

И ничего вот этого с _s не пишите. Ну его.

Понял, спасибо за совет)



0



Don’t worry, be happy

17779 / 10543 / 2035

Регистрация: 27.09.2012

Сообщений: 26,513

Записей в блоге: 1

11.07.2015, 16:01

12

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

Просто я список делаю не под консоль, а чтоб потом можно было удобно воспользоваться в полноценной программе.

Ну если уж такая полноценная программа, то может взять проверенный список из стандартной библиотеки (std::list)?



0



IrineK

Заблокирован

11.07.2015, 16:01

13

Какой UI будете использовать для «полноценной программы»?



0



81 / 25 / 19

Регистрация: 27.10.2014

Сообщений: 420

11.07.2015, 16:05

 [ТС]

14

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

Ну если уж такая полноценная программа, то может взять проверенный список из стандартной библиотеки (std::list)?

Ну на счет полноценности наверно переборщил, просто учусь создавать список, и вот хочу потом реализовать на более-менее программке

Добавлено через 1 минуту

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

Какой UI будете использовать для «полноценной программы»?

Windows Form



0



IrineK

Заблокирован

11.07.2015, 16:10

15

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

Windows Form

С++/CLI?
Это же managed CLR среда.
Вы собираетесь использовать нативные unmanaged вставки?



0



81 / 25 / 19

Регистрация: 27.10.2014

Сообщений: 420

11.07.2015, 16:26

 [ТС]

16

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

С++/CLI?
Это же managed CLR среда.
Вы собираетесь использовать нативные unmanaged вставки?

Да… наверно… как только разберусь что это)

Добавлено через 6 минут
Просто с++ я ток изучаю, вот придумал себе задание сделать список и с его помощью программу «работники», вводить, выводить преобразовывать, сортировать и т.д. данные.



0



IrineK

Заблокирован

11.07.2015, 16:41

17

Тогда все это не туда.
Еси вы хотите использовать CLR, то естественным языком будет C#. В котором. кстати, и строки юникодовские и готовые списки симпатишные.

Если вы хотите писать на С++ в Visual Studio, то и UI нужно брать нативную: WinAPI, MFC.
Или прикручивать к студии Qt.

В моём случае для С++ использую VCL. То бишь, работаю не в MS Visual Studio, а в Embarcadero RAD Studio.
Там будут вам и формочки, и кнопочки, и возможность использования нативного кода.



1



81 / 25 / 19

Регистрация: 27.10.2014

Сообщений: 420

11.07.2015, 18:37

 [ТС]

18

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

Еси вы хотите использовать CLR, то естественным языком будет C#.

Это я уже узнал, но так же пишут что С++/CLI идет как расширение с++. Как вы посоветуете, пытаться на с++ там что-то делать или поменять UI?

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

Если вы хотите писать на С++ в Visual Studio, то и UI нужно брать нативную: WinAPI, MFC.

WinAPI изучал, точнее пытался изучить, но сразу отпугивает его сложность и отсутствие конструктора в Студии.

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

В моём случае для С++ использую VCL.

Ну начинал я изучать в Borland`е, а он vcl-ый.

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

Embarcadero RAD Studio

Подойдет для меня как для новичка? Среда самодостаточна?



0



81 / 25 / 19

Регистрация: 27.10.2014

Сообщений: 420

12.07.2015, 12:06

 [ТС]

20

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

Так что — всё для вас будет знакомым.
Среда всегда была интересной и самодостаточной.

Вот интересно стало, а профессиональные программисты на сегодняшний день пользуются vcl и Embarcadero студией
в своих шедеврах?
Просто для меня эта среда нова, никогда о ней не слышал, потому и терзают сомнения…

Добавлено через 10 минут
Можете посоветовать туториалы, уроки, можно на английском…



0



  • Remove From My Forums

 locked

Debugging: Run-Time Check Failure #2 — Stack around the variable ‘LoggerThread’ was corrupted.

  • Question

  • I am getting:

    Run-Time Check Failure #2 — Stack around the variable ‘LoggerThread’ was corrupted.

    I have searched as much as I can for a description of how to diagnose, but I have not found anything. I don’t know how to determine the specific address that is being corrupted. If I knew that, then I could of course set a breakpoint on the condition of that changing.

    I have found many answers about other instances of this error, but nothing that descibes how to diagnose this problem. All other problems were simple enough that the problem could be determined by looking at the code. I have looked at my code extensively and I don’t see a problem. One of the previous answers I have found is Error: Stack corruption around the variable ‘tm’ but the current version of the program uses only default alignment.

    This particular problem is a symptom of a problem that has had various other symptoms, most of which would be more difficult to diagnose. Therefore the problem is probably more subtle than most. I initially encountered the problem in a DLL project, but I wrote a console program to use and test the relevant code. It is the console version that I am debugging.

Run-Time Check Failure #2 — Stack around the variable ‘grade’ was corrupted?

I wrote a program to calculate the average of 10 grades a user inputs. The program works and gives me the average, but at the end when it’s supposed to close I get this error: «Run-Time Check Failure #2 — Stack around the variable ‘grade’ was corrupted.»

I’ve posted the code below. Also, I have to make it calculate median and mode as well. I think I can figure out median, but can anyone help me to get started on mode?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
 {
	//Create an array with 10 elements
	float grade[10];
	int count;
	float tscore = 0;
	//Set precision of Average, will be displayed with a decimal
	double average;
	for (count = 1; count <= 10; count++)
	 {
		cout << "Enter Grade " << count << ": ";
		 {
		cin >> grade[count];
	 }}

	for(count = 1; count <= 10; count++)
		tscore = tscore + grade[count];
	average = tscore/10;
	
	//Assign letter grade corresponding to number grade
	if((average >= 0) && (average < 60))
	{
		cout<<"The average is an F."<<endl;
	}
	else if((average >= 60) && (average < 63))
	{
		cout<<"The average is a D-."<<endl;
	}
	else if((average >= 63) && (average < 67))
	{
		cout<<"The average is a D."<<endl;
	}
	else if((average >= 67) && (average < 70))
	{
		cout<<"The average is a D+."<<endl;
	}
	else if((average >= 70) && (average < 73))
	{
		cout<<"The average is a C-."<<endl;
	}
	else if((average >= 73) && (average < 77))
	{
		cout<<"The average is a C."<<endl;
	}
	else if((average >= 77) && (average < 80))
	{
		cout<<"The average is a C+."<<endl;
	}
	else if((average >= 80) && (average < 83))
	{
		cout<<"The average is a B-."<<endl;
	}
	else if((average >= 83) && (average < 87))
	{
		cout<<"The average is a B."<<endl;
	}
	else if((average >= 87) && (average < 90))
	{
		cout<<"The average is a B+."<<endl;
	}
	else if((average >= 90) && (average < 93))
	{
		cout<<"The average is an A-."<<endl;
	}
	else if((average >= 93) && (average < 97))
	{
		cout<<"The average is an A."<<endl;
	}
	else if((average >= 97) && (average <= 100))
	{
		cout<<"The average is an A+."<<endl;
	}
	else
	{
		cout<<"The average is not between 0 and 100, please reenter the grades with values between 0 and 100."<<endl;
	}

	//Output
	cout << "The average of the ten grades you entered is: " << average << endl;

	system("PAUSE"); 
	return 0;
}

Array indices go from 0 to n-1, not from 1 to n.

Thanks working now. Just one minor problem, it now says Enter Grade 0 for the first grade. Is there any simple way I can change that? If not, it’s fine how it is.

Also, how could I get the mode? Not asking for any code, just point me in the right direction. I know I’m going to have to use count, but not sure how to implement it.

Thanks

Last edited on

You could change it to cout << "Enter Grade " << count+1 << ": ";

As for the mode, there’s an STL algorithm called «count» that will return the amount of times something occurs in a range. Might be worth taking a look at http://www.cplusplus.com/reference/algorithm/count/

Last edited on

Still trying to figure that out, almost have median done though.

I need to move the median = … and the cout below to within the loop, but not sure where. Haven’t gotten a right answer anywhere I put it while testing.

Uses bubble sorting to order and then I take the middle two numbers (since its 10, even) and add them up and divide by 2.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
	//Calculate Median
	bool done;
	double temp;
	double median;
	while (done == false)
	{
	done = true;  //Done is a boolean value that is set to true by default, if it's left unchanged then we are done
	for (int i = 0; i < 9; i++)
		{
			if (grade[i] > grade[i+1])  //If the next value in the array is smaller than the current value, then we need to swap them.
				{
					temp = grade[i+1];  //Store the second value into a temporary variable first so we don't lose it
					grade[i+1] = grade[i];  //Then set the second value to the current value.
					grade[i] = temp;  //Afterwards place the stored temporary value into the current value
					done = false;   //Since we had to change a value, we are obviously not done, so when the loop completes, it will do another iteration.
	}
	}
	}
	median = (grade[5] + grade[6])/2;
	cout << "The median of the ten grades you entered is: " << median << endl;

Why would you want to move median = and cout into the loop? You only want to calculate it and output it once.

I guess that would be wrong too. Right now I’m getting a Runtime error and it’s outputting a median, but the median is wrong. It’s taking the median of grade[5] and grade[6] without ordering them.

Full code: (Median begins on line 89)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
// GradeMean.cpp : Defines the entry point for the console application.

#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
 {
	float grade[10]; //Create an array with 10 elements
	int count;
	float tscore = 0;
	double average;
	
	//Input Grades
	for (count = 0; count <= 9; count++)
	 {
		cout << "Enter Grade " << count+1 << ": ";
		 {
		cin >> grade[count];
	 }}

	//Calculate Average
	for(count = 0; count <= 9; count++)
		tscore = tscore + grade[count];
	average = tscore/10;
	
	//Assign letter grade corresponding to number grade
	if((average >= 0) && (average < 60)) 
	{
		cout<<"The average is an F."<<endl;
	}
	else if((average >= 60) && (average < 63))
	{
		cout<<"The average is a D-."<<endl;
	}
	else if((average >= 63) && (average < 67))
	{
		cout<<"The average is a D."<<endl;
	}
	else if((average >= 67) && (average < 70))
	{
		cout<<"The average is a D+."<<endl;
	}
	else if((average >= 70) && (average < 73))
	{
		cout<<"The average is a C-."<<endl;
	}
	else if((average >= 73) && (average < 77))
	{
		cout<<"The average is a C."<<endl;
	}
	else if((average >= 77) && (average < 80))
	{
		cout<<"The average is a C+."<<endl;
	}
	else if((average >= 80) && (average < 83))
	{
		cout<<"The average is a B-."<<endl;
	}
	else if((average >= 83) && (average < 87))
	{
		cout<<"The average is a B."<<endl;
	}
	else if((average >= 87) && (average < 90))
	{
		cout<<"The average is a B+."<<endl;
	}
	else if((average >= 90) && (average < 93))
	{
		cout<<"The average is an A-."<<endl;
	}
	else if((average >= 93) && (average < 97))
	{
		cout<<"The average is an A."<<endl;
	}
	else if((average >= 97) && (average <= 100))
	{
		cout<<"The average is an A+."<<endl;
	}
	else
	{
		cout<<"The average is not between 0 and 100, please reenter the grades with values between 0 and 100."<<endl;
	}

	//Output
	cout << "The average of the ten grades you entered is: " << average << endl;

	//Calculate Median
	bool done;
	double temp;
	double median;
	while (done == false)
	{
	done = true;  //Done is a boolean value that is set to true by default, if it's left unchanged then we are done
	for (int i = 0; i < 9; i++)
		{
			if (grade[i] > grade[i+1])  //If the next value in the array is smaller than the current value, then we need to swap them.
				{
					temp = grade[i+1];  //Store the second value into a temporary variable first so we don't lose it
					grade[i+1] = grade[i];  //Then set the second value to the current value.
					grade[i] = temp;  //Afterwards place the stored temporary value into the current value
					done = false;   //Since we had to change a value, we are obviously not done, so when the loop completes, it will do another iteration.
	}
	}
	}
	median = (grade[5] + grade[6])/2;
	cout << "The median of the ten grades you entered is: " << median << endl;

	//Calculate Mode
	

	system("PAUSE"); 
	return 0;
}

Last edited on

Array indices still go from 0 to n-1. grade[5] and grade[6] are the 6th and 7th elements, respectively.

I know, I changed it to 5 and 6 from 4 and 5. It would be 4 and 5 if I didn’t add 1 to count, so it should be 5 and 6, so I don’t think that’s the problem. Unless I’m missing something, which is definitely possible…

thanks

I don’t see where count comes into play in a expression like grade[5].
In any case, if what you’re trying to say is that the grades don’t get sorted, then that’s because you’re not initializing done, so it could be either true or false initially.

You’re got it backwards, cmorris1441.

In regular numbers:
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |

Array indices:
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |

Look vertically to see how the numbers correspond, If you want the 4th and 5th elements of the regular numbers, you’ll want to use indices 3 and 4.
so median = (grade[3] + grade[4])/2

Last edited on

You’re right, just changed it and entered 91-100 randomly (once each) and got a median of 94 though…

Also, I’m getting an error:
Run-Time Check Failure #3 — The variable ‘done’ is being used without being initialized.

Program still runs when I click continue.

Last edited on

The variable ‘done’ is being used without being initialized.

Believe it or not, but that’s directly related to the fact that you’re not initializing ‘done’.

It is now, I have 2 programs and was looking at the wrong one. Here’s what I now have, still not getting the median correct.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
// GradeMean.cpp : Defines the entry point for the console application.

#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
 {
	float grade[10]; //Create an array with 10 elements
	int count;
	float tscore = 0;
	double average;
	
	//Input Grades
	for (count = 0; count <= 9; count++)
	 {
		cout << "Enter Grade " << count+1 << ": ";
		 {
		cin >> grade[count];
	 }}

	//Calculate Mean
	for(count = 0; count <= 9; count++)
		tscore = tscore + grade[count];
	average = tscore/10;
	
	//Assign letter grade corresponding to number grade
	if((average >= 0) && (average < 60)) 
	{
		cout<<"The average is an F."<<endl;
	}
	else if((average >= 60) && (average < 63))
	{
		cout<<"The average is a D-."<<endl;
	}
	else if((average >= 63) && (average < 67))
	{
		cout<<"The average is a D."<<endl;
	}
	else if((average >= 67) && (average < 70))
	{
		cout<<"The average is a D+."<<endl;
	}
	else if((average >= 70) && (average < 73))
	{
		cout<<"The average is a C-."<<endl;
	}
	else if((average >= 73) && (average < 77))
	{
		cout<<"The average is a C."<<endl;
	}
	else if((average >= 77) && (average < 80))
	{
		cout<<"The average is a C+."<<endl;
	}
	else if((average >= 80) && (average < 83))
	{
		cout<<"The average is a B-."<<endl;
	}
	else if((average >= 83) && (average < 87))
	{
		cout<<"The average is a B."<<endl;
	}
	else if((average >= 87) && (average < 90))
	{
		cout<<"The average is a B+."<<endl;
	}
	else if((average >= 90) && (average < 93))
	{
		cout<<"The average is an A-."<<endl;
	}
	else if((average >= 93) && (average < 97))
	{
		cout<<"The average is an A."<<endl;
	}
	else if((average >= 97) && (average <= 100))
	{
		cout<<"The average is an A+."<<endl;
	}
	else
	{
		cout<<"The average is not between 0 and 100, please reenter the grades with values between 0 and 100."<<endl;
	}

	//Output
	cout << "The average of the ten grades you entered is: " << average << endl;

	//Calculate Median
	bool done = false;
	double temp;
	double median;
	while (done == false)
	{
	done = true;  //Done is a boolean value that is set to true by default, if it's left unchanged then we are done
	for (int i = 0; i < 9; i++)
		{
			if (grade[i] > grade[i+1])  //If the next value in the array is smaller than the current value, then we need to swap them.
				{
					temp = grade[i+1];  //Store the second value into a temporary variable first so we don't lose it
					grade[i+1] = grade[i];  //Then set the second value to the current value.
					grade[i] = temp;  //Afterwards place the stored temporary value into the current value
					done = false;   //Since we had to change a value, we are obviously not done, so when the loop completes, it will do another iteration.
	}
	}
	}
	median = (grade[3] + grade[4])/2;
	cout << "The median of the ten grades you entered is: " << median << endl;

	//Calculate Mode
	

	system("PAUSE"); 
	return 0;
}

Last edited on

The two middle elements are the ones with indices 4 and 5.

Okay, the confusion ends here. I didn’t count to the middle of the array properly.
median = (grade[4] + grade[5])/2
Reference my little diagram above. Numbers correspond vertically. We both should have seen that. Lol.

Wasn’t thinking when I corrected it earlier. Thanks. Median and Mean both work now.

Thanks Athar and Thumper for all the help.

Oops, disregard. 🙂

Last edited on

Topic archived. No new replies allowed.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка stabili track opel astra j
  • Ошибка sta на реле напряжения