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
![]()
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 (
freefor something allocated withnew, 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 HammenDavid Hammen
32k8 gold badges59 silver badges107 bronze badges
This can be caused by several issues, that are generally hard to see:
- double deletes
deletea variable allocated withnew[]ordelete[]a variable allocated withnewdeletesomething allocated withmallocdeletean 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 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
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
![]()
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
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
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
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
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
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
20.4k3 gold badges51 silver badges86 bronze badges
asked Feb 27, 2011 at 20:57
1
location is an array of a single char.
There is no location[1].
answered Feb 27, 2011 at 21:00
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 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 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
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, а пользователь имел доступ только к функциям добавления, удаления и т.д. Все было хорошо, но вот столкнулся с проблемой после завершения программы всегда пишет: Кликните здесь для просмотра всего текста
Кликните здесь для просмотра всего текста
Если не трудно гляньте, может еще ошибок понаделал.
__________________
0 |
|
Заблокирован |
|
|
10.07.2015, 18:23 |
2 |
|
Не выделяете памяти под строки: ни в main, ни в add
0 |
|
valeriy007 81 / 25 / 19 Регистрация: 27.10.2014 Сообщений: 420 |
||||
|
10.07.2015, 18:31 [ТС] |
3 |
|||
|
Не выделяете памяти под строки: ни в main, ни в add
Так будет правильно? В add думаю не надо, ведь в функцию передаю только адрес.
0 |
|
858 / 447 / 112 Регистрация: 06.07.2013 Сообщений: 1,495 |
|
|
10.07.2015, 18:44 |
4 |
|
char *a = new char[]; в квадратных скобках нужно указать под сколько букв нужно выделить память
0 |
|
81 / 25 / 19 Регистрация: 27.10.2014 Сообщений: 420 |
|
|
10.07.2015, 18:52 [ТС] |
5 |
|
в квадратных скобках нужно указать под сколько букв нужно выделить память просто хотелось бы вводить без ограничений, то есть сколько ввел, столько и вывел…
0 |
|
Заблокирован |
||||||||
|
10.07.2015, 19:26 |
6 |
|||||||
|
Можно сказать я не знаю сколько пользователь введет в строку букв… Вот это
означает, что выделен 1 байт памяти: на конец строки. Сделайте нормальный буфер. Скажем
Вот это
std::cin >> a; означает, что «Вася Пупкин» вы не введете, даже если предоставите необходимый буфер. Добавлено через 9 минут
В add думаю не надо, ведь в функцию передаю только адрес Адрес чего? И где оно лежит? И где лежать будет?
0 |
|
valeriy007 81 / 25 / 19 Регистрация: 27.10.2014 Сообщений: 420 |
||||
|
10.07.2015, 22:17 [ТС] |
7 |
|||
|
Пользователю развернуться негде. А если так?
Адрес чего? И где оно лежит? И где лежать будет? Адрес «а» по которому элемент добавляется в список.
0 |
|
Заблокирован |
||||
|
10.07.2015, 23:04 |
8 |
|||
|
В рамках данного кода
Чтобы закончить ввод, введите пустую строку. Ну, и нужно написать очистку памяти.
0 |
|
valeriy007 81 / 25 / 19 Регистрация: 27.10.2014 Сообщений: 420 |
||||||||||||
|
11.07.2015, 14:38 [ТС] |
9 |
|||||||||||
|
Это как я понял для правильно ввода в консоли. Просто я список делаю не под консоль, а чтоб потом можно было удобно воспользоваться в полноценной программе.
Ну, и нужно написать очистку памяти. Очистку памяти от всего списка? Объясните немного про BUFSIZ… Вместо него можно просто написать 512?. В нете почитал, он используется в основном при работе с файлами… Добавлено через 1 час 16 минут
Тут сложилась такая ситуация:
0 |
|
Заблокирован |
||||
|
11.07.2015, 15:50 |
10 |
|||
|
Я правильно воспользовался ею?) Вы еще и в студии?
И ничего вот этого с _s не пишите. Ну его.
в полноценной программе. Там будет кириллица?
0 |
|
81 / 25 / 19 Регистрация: 27.10.2014 Сообщений: 420 |
|
|
11.07.2015, 15:58 [ТС] |
11 |
|
Там будет кириллица? да
И ничего вот этого с _s не пишите. Ну его. Понял, спасибо за совет)
0 |
|
Don’t worry, be happy 17779 / 10543 / 2035 Регистрация: 27.09.2012 Сообщений: 26,513 Записей в блоге: 1 |
|
|
11.07.2015, 16:01 |
12 |
|
Просто я список делаю не под консоль, а чтоб потом можно было удобно воспользоваться в полноценной программе. Ну если уж такая полноценная программа, то может взять проверенный список из стандартной библиотеки (std::list)?
0 |
|
Заблокирован |
|
|
11.07.2015, 16:01 |
13 |
|
Какой UI будете использовать для «полноценной программы»?
0 |
|
81 / 25 / 19 Регистрация: 27.10.2014 Сообщений: 420 |
|
|
11.07.2015, 16:05 [ТС] |
14 |
|
Ну если уж такая полноценная программа, то может взять проверенный список из стандартной библиотеки (std::list)? Ну на счет полноценности наверно переборщил, просто учусь создавать список, и вот хочу потом реализовать на более-менее программке Добавлено через 1 минуту
Какой UI будете использовать для «полноценной программы»? Windows Form
0 |
|
Заблокирован |
|
|
11.07.2015, 16:10 |
15 |
|
Windows Form С++/CLI?
0 |
|
81 / 25 / 19 Регистрация: 27.10.2014 Сообщений: 420 |
|
|
11.07.2015, 16:26 [ТС] |
16 |
|
С++/CLI? Да… наверно… как только разберусь что это) Добавлено через 6 минут
0 |
|
Заблокирован |
|
|
11.07.2015, 16:41 |
17 |
|
Тогда все это не туда. Если вы хотите писать на С++ в Visual Studio, то и UI нужно брать нативную: WinAPI, MFC. В моём случае для С++ использую VCL. То бишь, работаю не в MS Visual Studio, а в Embarcadero RAD Studio.
1 |
|
81 / 25 / 19 Регистрация: 27.10.2014 Сообщений: 420 |
|
|
11.07.2015, 18:37 [ТС] |
18 |
|
Еси вы хотите использовать CLR, то естественным языком будет C#. Это я уже узнал, но так же пишут что С++/CLI идет как расширение с++. Как вы посоветуете, пытаться на с++ там что-то делать или поменять UI?
Если вы хотите писать на С++ в Visual Studio, то и UI нужно брать нативную: WinAPI, MFC. WinAPI изучал, точнее пытался изучить, но сразу отпугивает его сложность и отсутствие конструктора в Студии.
В моём случае для С++ использую VCL. Ну начинал я изучать в Borland`е, а он vcl-ый.
Embarcadero RAD Studio Подойдет для меня как для новичка? Среда самодостаточна?
0 |
|
81 / 25 / 19 Регистрация: 27.10.2014 Сообщений: 420 |
|
|
12.07.2015, 12:06 [ТС] |
20 |
|
Так что — всё для вас будет знакомым. Вот интересно стало, а профессиональные программисты на сегодняшний день пользуются vcl и Embarcadero студией Добавлено через 10 минут
0 |
- Remove From My Forums
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?
|
|
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.
|
|
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)
|
|
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.
|
|
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.

