I have an infinite loop that breaks if user exits out of the main window. I have the following code running in the loop:
unsigned int* renderableShapeIndices = new unsigned int[aNumberCreatedAtRuntime];
// Do something
delete[] renderableShapeIndices;
Then the following happens a couple of loop iterations and cease to happen after the first iteration:
1st breakpoint:
A breakpoint instruction (__debugbreak() statement or a similar call) was executed in Main.exe.
2nd breakpoint:
Unhandled exception at 0x00007FF8C3B8C729 (ntdll.dll) in InTimeEngine2D.exe: 0xC0000374: A heap has been corrupted (parameters: 0x00007FF8C3BF7780).
Has anyone else gone through similar issues? I have no idea what is going on.
Another interesting factor about this is that it only happens in debug mode. It does not happen in release mode.
asked Jun 17, 2022 at 4:39
6
The answer to the problem is in the comment section of the question.
Apparently, if one attempts to write to an array outside of its bounds, it will, but it ends up overwriting data of other places in the code, causing bugs in other parts of the program, even if these two parts of the program are unrelated. In my case, they were completely unrelated.
answered Jun 17, 2022 at 5:28
3
Перейти к контенту
I have an infinite loop that breaks if user exits out of the main window. I have the following code running in the loop:
unsigned int* renderableShapeIndices = new unsigned int[aNumberCreatedAtRuntime];
// Do something
delete[] renderableShapeIndices;
Then the following happens a couple of loop iterations and cease to happen after the first iteration:
1st breakpoint:
A breakpoint instruction (__debugbreak() statement or a similar call) was executed in Main.exe.
2nd breakpoint:
Unhandled exception at 0x00007FF8C3B8C729 (ntdll.dll) in InTimeEngine2D.exe: 0xC0000374: A heap has been corrupted (parameters: 0x00007FF8C3BF7780).
Has anyone else gone through similar issues? I have no idea what is going on.
Another interesting factor about this is that it only happens in debug mode. It does not happen in release mode.
asked Jun 17, 2022 at 4:39
6
The answer to the problem is in the comment section of the question.
Apparently, if one attempts to write to an array outside of its bounds, it will, but it ends up overwriting data of other places in the code, causing bugs in other parts of the program, even if these two parts of the program are unrelated. In my case, they were completely unrelated.
answered Jun 17, 2022 at 5:28
4
|
Egefix 12 / 10 / 2 Регистрация: 24.05.2022 Сообщений: 115 |
||||
|
1 |
||||
|
03.06.2022, 01:52. Показов 5650. Ответов 2 Метки нет (Все метки)
во время выполнения происходит это: Critical error detected c0000374
0 |
|
Egefix 12 / 10 / 2 Регистрация: 24.05.2022 Сообщений: 115 |
||||
|
03.06.2022, 01:56 [ТС] |
2 |
|||
Добавлено через 3 минуты Добавлено через 30 секунд 0 |
|
6314 / 3933 / 1577 Регистрация: 09.05.2015 Сообщений: 9,235 |
|
|
03.06.2022, 02:09 |
3 |
|
У вас в перепутаны длины массивов… 1 |
У меня есть бесконечный цикл, который прерывается, если пользователь выходит из главного окна. У меня в цикле работает следующий код:
unsigned int* renderableShapeIndices = new unsigned int[aNumberCreatedAtRuntime];
// Do something
delete[] renderableShapeIndices;
Затем происходит следующее через пару итераций цикла и перестает происходить после первой итерации:
1st breakpoint:
A breakpoint instruction (__debugbreak() statement or a similar call) was executed in Main.exe.
2nd breakpoint:
Unhandled exception at 0x00007FF8C3B8C729 (ntdll.dll) in InTimeEngine2D.exe: 0xC0000374: A heap has been corrupted (parameters: 0x00007FF8C3BF7780).
Кто-нибудь еще сталкивался с подобными проблемами? Я понятия не имею, что происходит.
Еще одним интересным фактором является то, что это происходит только в режиме отладки. Это не происходит в режиме выпуска.
1 ответ
Лучший ответ
Ответ на проблему находится в разделе комментариев вопроса.
По-видимому, если кто-то попытается записать в массив за пределами его границ, это произойдет, но в конечном итоге это приведет к перезаписи данных в других местах кода, что вызовет ошибки в других частях программы, даже если эти две части программы не связаны. . В моем случае они были совершенно не связаны.
0
Christopher Barrios Agosto
17 Июн 2022 в 08:28
Результат будет выглядеть примерно так (главное — видны пути к файлам и видны значения параметров)
ole32.dll!OleUninitialize()Строка 557
в comole32ole232baseole2.cpp(557)
mir_core.mir!LeaveMessageLoop()Строка 362
в w:miranda-buildsrcmir_coresrcwindowsmiranda.cpp(362)
mir_app.mir!mir_main(wchar_t * cmdLine)Строка 226
в w:miranda-buildsrcmir_appsrcmiranda.cpp(226)
Miranda64.exe!wWinMain(HINSTANCE__ * __formal=0x0000000000000001, HINSTANCE__ * __formal=0x000000000014fe70, wchar_t * cmdLine=0x00000000005e6d3c, int __formal=96)Строка 62
в w:miranda-buildsrcmiranda32srcmiranda.cpp(62)
[Внешний код]
В приложении, использующем OpenTK, при включении встроенной отладки и нажатии F12 отладчик ломается:
Инструкция точки останова (оператор __debugbreak() или аналогичный вызов) была выполнена в …
Стек вызовов не очень помогает определить причину:
ntdll.dll!DbgBreakPoint()
ntdll.dll!DbgUiRemoteBreakin()
kernel32.dll!BaseThreadInitThunk()
ntdll.dll!RtlUserThreadStart()
Сначала я подумал, что это связано с AeDebug, однако это не так:
- изменение Auto ничего не дает
- изменение UserDebuggerHotKey ничего не делает
- изменение отладчика ничего не дает
- перезагрузка компьютера, сброс параметров Visual Studio ничего не делает
Простейшее приложение , где это происходит :
using OpenTK.Graphics.OpenGL;
using OpenTK.Mathematics;
using OpenTK.Windowing.Common;
using OpenTK.Windowing.Desktop;
using OpenTK.Windowing.GraphicsLibraryFramework;
using var window = new MyGameWindow(GameWindowSettings.Default, NativeWindowSettings.Default);
window.Run();
public class MyGameWindow : GameWindow {
public MyGameWindow(GameWindowSettings gameWindowSettings, NativeWindowSettings nativeWindowSettings)
: base(gameWindowSettings, nativeWindowSettings) { }
private double TotalTime { get; set; }
protected override void OnUpdateFrame(FrameEventArgs args) {
TotalTime += args.Time;
if (KeyboardState[Keys.F12])
TotalTime = 0;
}
protected override void OnRenderFrame(FrameEventArgs args) {
GL.Clear(ClearBufferMask.ColorBufferBit);
GL.ClearColor(Color4.FromHsv(new Vector4((float)TotalTime % 10f / 10f, 1.0f, 0.5f, 1.0f)));
SwapBuffers();
}
protected override void OnResize(ResizeEventArgs e) {
base.OnResize(e);
GL.Viewport(0, 0, e.Width, e.Height);
}
}
запускSettings.json:
{
"profiles": {
"DebugBreakF12": {
"commandName": "Project",
"nativeDebugging": true
}
}
}
Вопрос:
Как можно отключить__debugbreakповедение при нажатии клавиши F12?
Или я должен просто забыть использовать клавишу F12, когда включена собственная отладка?
Привет. Возникла проблема с перегруженным оператором.
По сути он все складывает
и строку присваивает правильно (в тестовом выводе всё гуд), но на отладке, после выполнения возвращения, он меняет сроку на другую, рандомной длины.
И после завершения программы выдаёт ошибку delete_scalar.cpp
Что не так?
Date Date::operator+(const Date& other) const
{
int new_date = date + other.date;
int new_month = month + other.month;
int new_year = year + other.year;
char word[] = «Unknown»;
Date new_date_obj { new_date, new_month, new_year, word };
new_date_obj.print();
return new_date_obj;
}
russian
web-design
15
ответов
Оберните код в теги: 3 символа ` до и после кода (в случае одиночной конструкции достаточно 1 ` с обеих сторон). Спасибо!
тут все не так. начиная с сигнатуры вашего оператора
Всё ещё неправильно 
Всё ещё неправильно 
Мне кажется, не хватает текста ошибки.
А еще конструкторов и деструктора, при наличии
Mikail Bagishov
Мне кажется, не хватает текста ошибки.
А еще конс…
Ошибка : Инструкция точки останова (оператор __debugbreak() или аналогичный вызов) выполнена в Date1.exe.
Date::Date(int date, int month, int year, char* day_of_week)
{
this->date = date;
this->month = month;
this->year = year;
this->day_of_week = new char[strlen(day_of_week) + 1];
strcpy(this->day_of_week, day_of_week);
this->day_of_week[strlen(day_of_week)] = ‘\0’;
}
Date::~Date()
{
delete[] day_of_week;
}
Nickolas Valentine
Ошибка : Инструкция точки останова (оператор __deb…
А копирующий/перемещающий конструкторы?
Nickolas Valentine
Ошибка : Инструкция точки останова (оператор __deb…
Вы на c++ пишите. Используйте нормальные строки.
Nickolas Valentine
Ошибка : Инструкция точки останова (оператор __deb…
ещё и инициализировать можно вот так
Date(int date) : date(date)
Андрей Будиловский
Тогда он не прострелит себе ноги
Если я использую стринг, тогда лектор прострелит мне ноги
Nickolas Valentine
Если я использую стринг, тогда лектор прострелит м…
не используй указатели, хотя бы по ссылке передавай. Или копируй, так точно ноги останутся целы
Nickolas Valentine
Если я использую стринг, тогда лектор прострелит м…
Хорошо, тогда следуй правилу 5:
— Копирующий конструктор
— Перемешающие конструктор
— Копирующий оператор присваивания
— Перемешающие оператор присваивания
— Деструктор
Если в классе объявлено (или заделичено) хотя бы одно, то надо объявить (или заделитить) и все остальное
Aniki Hi$ok@ 🌈 Z 🐀
не используй указатели, хотя бы по ссылке передава…
В этом случае ноги так же будут прострелены, мне нужно использовать указатель
Trying to Figure out how to fix this error: A breakpoint instruction (__debugbreak() statement or a similar call) was executed
SOLVED
I have a program with coded that was given to me that creates a file and generates random value and writes them to the file. So i need to sort these values using whatever sorting algorithm. So i decided to store those values in a dynamic array; using the new keyword in order to pass them in to functions to sort them but i keep getting this error message A breakpoint instruction (__debugbreak() statement or a similar call) was executed.
arr = new int(nums); //array decloration arrT2 = new int(nums);
[outfile.open](https://outfile.open)(filename.c\_str(), ios::binary); // open the file
for (i = 0; i < nums; i++) { // loop to generate the numbers
theNum = rand() % 100000000; // generate an integer value up to 100M
outfile.write((char\*)&theNum, sizeof(int)); // store the value
arr\[i\] = theNum;
arrT2\[i\] = theNum;
}
outfile.close(); // close the file
clock\_t c\_start = clock(); // start timer insertionSort(arr, nums); //print(arr, nums); clock\_t c\_end = clock(); //end timer
long double time\_elapsed\_sec = (c\_end - c\_start) / CLOCKS\_PER\_SEC; cout << "CPU time used: " << time\_elapsed\_sec << "seconds" << endl;
clock\_t c\_start\_b = clock(); quickSort(arrT2, 0, nums); // 0 is beginning and nums is the last since its the amount stored in the array //print(arrT2, 6); clock\_t c\_end\_b = clock();
long double time\_elapsed\_sec\_b = (c\_end\_b - c\_start\_b) / CLOCKS\_PER\_SEC; cout << "CPU time used: " << time\_elapsed\_sec\_b << "seconds" << endl;
Locked post. New comments cannot be posted.
Я работаю с сторонней C ++ DLL, которая в некоторых случаях выполняет __debugbreak () и не проверяет IsDebuggerPresent () перед этим. Это приводит к сбою моего приложения, когда этот сценарий происходит вне отладчика (например, конечный пользователь, выполняющий приложение). Я хотел бы поймать это и разобраться с этим сам, или, по крайней мере, игнорировать это.
У меня на самом деле был фильтр необработанных исключений, чтобы некоторое время переводить исключения SEH в C ++, поэтому немного странно, что он не работает.
::SetUnhandledExceptionFilter(OnUnhandledException);
Я проводил некоторое прямое тестирование, и стандарт __try / __, за исключением работы, поэтому я мог обернуть каждый вызов в DLL с этим как запасной вариант, но, похоже, что если __try / __ кроме работает, то также работа.
__try
{
__debugbreak();
}
__except (EXCEPTION_EXECUTE_HANDLER)
{
printf("caught");
}
try / catch (…) не работает.
try
{
__debugbreak();
}
catch (...)
{
printf("caught");
}
_set_se_translator () тоже не работает.
Из документации MSDN на https://msdn.microsoft.com/en-us/library/ms679297(VS.85).aspx в нем говорится, что оно должно функционировать как структурированное исключение. Я понимаю, что это документация для DebugBreak (), но я протестировал и это, и у меня та же проблема, даже с «catch (…)».
Я компилирую с / EHa.
Как я могу поймать __debugbreak (asm INT 3) или хотя бы изменить поведение?
2
Решение
Точки останова генерируют EXCEPTION_BREAKPOINT структурированное исключение. Вы не можете использовать try / catch, чтобы поймать его, потому что он не переводится в исключение C ++, независимо от параметра / EHa или _set_se_translator, EXCEPTION_BREAKPOINT это особое исключение.
Во-первых, вы должны знать, что блоки catch и __except выполняются только после разматывания стека. Это означает, что выполнение продолжается после блока обработчика, а НЕ после вызова __debugbreak(), Так что, если вы просто хотите пропустить EXCEPTION_BREAKPOINT в то же время продолжить выполнение после int 3 инструкция. Вы должны использовать векторный обработчик исключений. Вот пример:
// VEH is supported only on Windows XP+ and Windows Server 2003+
#define _WIN32_WINNT 0x05020000
#include <windows.h>
#include <stdio.h>
//AddVectoredExceptionHandler constants:
//CALL_FIRST means call this exception handler first;
//CALL_LAST means call this exception handler last
#define CALL_FIRST 1
#define CALL_LAST 0
LONG WINAPI
VectoredHandlerBreakPoint(
struct _EXCEPTION_POINTERS *ExceptionInfo
)
{
if (ExceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT)
{
/*
If a debugger is attached, this will never be executed.
*/
printf("BreakPoint at 0x%x skipped.\n", ExceptionInfo->ExceptionRecord->ExceptionAddress);
PCONTEXT Context = ExceptionInfo->ContextRecord;
// The breakpoint instruction is 0xCC (int 3), just one byte in size.
// Advance to the next instruction. Otherwise, this handler will just be called ad infinitum.
#ifdef _AMD64_
Context->Rip++;
#else
Context->Eip++;
#endif
// Continue execution from the instruction at Context->Rip/Eip.
return EXCEPTION_CONTINUE_EXECUTION;
}
// IT's not a break intruction. Continue searching for an exception handler.
return EXCEPTION_CONTINUE_SEARCH;
}
void main()
{
// Register the vectored exception handler once.
PVOID hVeh = AddVectoredExceptionHandler(CALL_FIRST, VectoredHandlerBreakPoint);
if (!hVeh)
{
// AddVectoredExceptionHandler failed.
// Practically, this never happens.
}
DebugBreak();
// Unregister the handler.
if (hVeh)
RemoveVectoredExceptionHandler(hVeh);
}
Таким образом, инструкция точки останова int 3 будет просто пропущен и следующая инструкция будет выполнена. Также, если отладчик подключен, он будет обрабатывать EXCEPTION_BREAKPOINT для тебя.
Однако, если вы действительно хотите размотать стек, вы должны использовать __except(GetExceptionCode() == EXCEPTION_BREAKPOINT ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH),
5
Другие решения
Других решений пока нет …
Although not needed for small arrays, and since there are answers based on the questions code, here is a somewhat optimized top down merge sort that avoids copy backs by using a pair of mutually recursive functions (…a2a, …a2b). An entry function does a one time allocation of the temporary array. On my system, it takes less than .5 second to sort an array of 4 million structures.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct EntryStruct {
int data;
char *name;
} Entry;
/* prototypes for mutually recursive functions */
void merge_sort_a2a(Entry *a, Entry *b, int ll, int ee);
void merge_sort_a2b(Entry *a, Entry *b, int ll, int ee);
void merge(Entry *a, Entry *b, int ll, int rr, int ee)
{
int o = ll; /* b[] index */
int l = ll; /* a[] left index */
int r = rr; /* a[] right index */
while(1){
if(a[l].data <= a[r].data){ /* if a[l] <= a[r] */
b[o++] = a[l++]; /* copy a[l] */
if(l < rr) /* if not end of left run */
continue; /* continue (back to while) */
while(r < ee) /* else copy rest of right run */
b[o++] = a[r++];
break; /* and return */
} else { /* else a[l] > a[r] */
b[o++] = a[r++]; /* copy a[r] */
if(r < ee) /* if not end of right run */
continue; /* continue (back to while) */
while(l < rr) /* else copy rest of left run */
b[o++] = a[l++];
break; /* and return */
}
}
}
void merge_sort_a2a(Entry *a, Entry *b, int ll, int ee)
{
int rr;
if(ee - ll < 2){ /* if 1 element */
return; /* return */
}
rr = ll + (ee-ll)/2; /* mid point, start of right run */
merge_sort_a2b(a, b, ll, rr);
merge_sort_a2b(a, b, rr, ee);
merge(b, a, ll, rr, ee);
}
void merge_sort_a2b(Entry *a, Entry *b, int ll, int ee)
{
int rr;
if(ee - ll < 2){ /* if 1 element */
b[ll] = a[ll]; /* copy to b */
return;
}
rr = ll + (ee-ll)/2; /* mid point, start of right run */
merge_sort_a2a(a, b, ll, rr);
merge_sort_a2a(a, b, rr, ee);
merge(a, b, ll, rr, ee);
}
void merge_sort(Entry *a, int n) {
if(n < 2)
return;
Entry *b = malloc(n * sizeof(Entry));
merge_sort_a2a(a, b, 0, n);
free(b);
}
Entry Entry_create(int data, const char *name) {
Entry node;
node.name = _strdup(name); /* _strdup is ISO name */
node.data = data;
return node;
}
void printArrByName(Entry *arr, int n) {
for (int i = 0; i < n; i++) {
printf("%s\n", arr[i].name);
}
}
int main(void) {
Entry *arr = malloc(5 * sizeof(*arr));
arr[0] = Entry_create(5, "abc");
arr[1] = Entry_create(6, "def");
arr[2] = Entry_create(2, "ghijk");
arr[3] = Entry_create(3, "ksdljf");
arr[4] = Entry_create(1, "lsdfjl");
merge_sort(arr, 5);
printArrByName(arr, 5);
for (int i = 0; i < 5; i++)
free(arr[i].name);
free(arr);
return 0;
}
