DGDarkKing 9 / 8 / 1 Регистрация: 23.11.2019 Сообщений: 141 |
||||
1 |
||||
17.05.2021, 08:26. Показов 3363. Ответов 4 Метки критическая ошибка, память, работа с памятью (Все метки)
Добрый день! Вот код(ошибку выдаёт при попытке вывести в консоль первый элемент, дальше программа естественно не идёт)
Добавлено через 51 секунду
__________________
0 |
stdin 129 / 81 / 49 Регистрация: 10.01.2020 Сообщений: 293 |
||||
17.05.2021, 08:36 |
2 |
|||
DGDarkKing, под двухмерный динамический массив память выделяется так:
0 |
Annemesski 2438 / 1177 / 436 Регистрация: 08.11.2016 Сообщений: 3,251 |
||||
17.05.2021, 12:44 |
3 |
|||
Сообщение было отмечено DGDarkKing как решение Решение
1 |
9 / 8 / 1 Регистрация: 23.11.2019 Сообщений: 141 |
|
17.05.2021, 15:52 [ТС] |
4 |
это я знаю, мне нужена именно псевдо матрица Добавлено через 36 секунд
под двухмерный динамический массив память выделяется так: это я знаю, мне нужна именно псевдо матрица
0 |
zss Модератор 12640 / 10134 / 6102 Регистрация: 18.12.2011 Сообщений: 27,170 |
||||||||
17.05.2021, 17:30 |
5 |
|||||||
arr[i * N + j] = rand() % 100;
и
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
17.05.2021, 17:30 |
Помогаю со студенческими работами здесь Критическая ошибка Был бы очень признателен за любую помощь! Неожиданно случилась… Критическая ошибка Критическая ошибка Критическая ошибка Критическая ошибка в С Критическая ошибка. WS2016 Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 5 |
Как исправить ошибку Windows C0000374 Ошибка C0000374
В этой статье рассматривается ошибка C0000374, также известная как Ошибка C0000374 и означающая
Об ошибке Windows
Операционная система Windows сегодня используется миллионами пользователей персональных компьютеров и ноутбуков. И вполне вероятно, что большинство из них в свое время сталкивались с тем или иным типом ошибки Windows. Отчеты об ошибках были представлены компанией Microsoft для обеспечения средств сбора и отправки отладочной информации после ошибки или для применения шагов по устранению неполадок в зависимости от того, получил ли пользователь синтаксическую, логическую ошибку или ошибку времени выполнения.
Если пользователь получает код остановки, то вместе с сообщением об ошибке предоставляется краткая информация по устранению неполадок. Затем пользователь может найти конкретное сообщение об ошибке и применить исправление, предоставленное на сайтах поддержки Microsoft, а также в других доступных в Интернете статьях и журналах по данной теме.
В других случаях пользователь получает только уведомление о сбое компьютера, после чего ему предлагается отправить отчет о сбое в Microsoft. Это делается для сбора данных для анализа, чтобы компания Microsoft могла отправить пользователю решение проблемы.
Каким бы ни был случай, вот некоторые общие сведения об устранении неполадок, которые можно использовать для устранения ошибок Windows.
Симптомы C0000374 — Ошибка C0000374
Ошибки Windows можно классифицировать как синтаксические ошибки, логические ошибки или ошибки времени выполнения.
Когда пользователь получает синтаксическую ошибку, компьютер просто внезапно выдает сообщение об ошибке, что в фоновом режиме произошел сбой. Программы, к которым обращается пользователь, могут застопориться или полностью завершиться. Пользователь может продолжать использовать другие приложения, но время от времени появляется непонятное сообщение о том, что запущенная программа не может запуститься, потому что какой-то процесс не работает.
Ошибки времени выполнения происходят во время работы приложения. Поэтому, когда ошибка возникает, она просто происходит без предупреждения, и компьютер выдает уведомление о том, что произошла ошибка.
Логические ошибки связаны с программированием. Ошибка вызывает непреднамеренный вывод или поведение. Если говорить о компьютерных системах, которые прошли все испытания и поступили в продажу, то логические ошибки случаются только тогда, когда произошли значительные изменения в физическом состоянии логической платы. Возможно, часть шин расплавилась или возникла подобная ситуация. Это может привести к тому, что компьютер внезапно издаст громкий звуковой сигнал или скрежещущий звук, и даже может перейти к внезапной нестабильной работе, замерзнуть или резко изменить температуру перед фактическим сбоем.
(Только для примера)
Причины ошибок Ошибка C0000374 — C0000374
Ошибки Windows могут быть вызваны неисправностью аппаратных компонентов или повреждением ОС. Некоторые из них могут быть даже связаны с проблемами программирования, которые не были решены, поскольку ошибки не были устранены на этапе проектирования. Иногда ошибки Windows могут возникать из-за изменений, внесенных в компьютер.
Методы исправления
Для разных категорий ошибок Windows существуют разные шаги по устранению неполадок. Однако существуют общие шаги, которые можно применить, столкнувшись с этими ошибками. Вот они.
Если метод ремонта вам подошел, пожалуйста, нажмите кнопку upvote слева от ответа, это позволит другим пользователям узнать, какой метод ремонта на данный момент работает лучше всего.
Обратите внимание: ни ErrorVault.com, ни его авторы не несут ответственности за результаты действий, предпринятых при использовании любого из методов ремонта, перечисленных на этой странице — вы выполняете эти шаги на свой страх и риск.
Метод 1 — Восстановить базу данных Центра обновления Windows
Когда хороший компьютер внезапно начинает работать странным образом, причиной могут быть обновления Windows. Чтобы исправить это, пользователи могут запустить Восстановление системы, если есть дата восстановления, сохраненная до ошибки. Вот как это делается.
Восстановление в Windows 7:
- Нажмите Пуск и введите Восстановление системы в поле поиска, затем нажмите клавишу ввода.
- Когда появится окно восстановления системы, нажимайте Далее , пока не дойдете до окна, в котором вы можете выбрать точку восстановления. Вы увидите список дат восстановления с описанием.
- Затем снова нажмите Далее и подтвердите процесс восстановления. Подождите, пока он прекратит обработку, и появится окно, в котором вы можете нажать кнопку Готово . Закройте окно и дайте компьютеру перезагрузиться.
Вы также можете восстановить свой компьютер с помощью установочного диска ОС .
- Для этого загрузитесь с компакт-диска с ОС или с носителя для восстановления.
- Следуйте инструкциям, пока не дойдете до экрана, на котором будет предложена опция Восстановить мой компьютер , нажмите и выберите Восстановление системы из списка инструментов восстановления.
- Вы можете выбрать любую точку восстановления в окне «Восстановление системы», но убедитесь, что вы восстановили дату, при которой ваш компьютер работает нормально.
- Дождитесь завершения процесса и позвольте вашему компьютеру перезагрузиться на рабочий стол.
Вы также можете загрузиться в безопасном режиме .
- Загрузите компьютер и нажмите F8. Выберите Безопасный режим с командной строкой , нажимая стрелки на клавиатуре, чтобы переместить выделение вниз к этому элементу.
- В безопасном режиме введите rstrui.exe и нажмите Enter в командной строке. Следуйте указаниям мастера восстановления и перезагрузите компьютер в обычном режиме.
Восстановление в Windows 8:
Восстановление в среде Windows
- В Windows 8 щелкните значок поиска и введите Восстановление системы.
- Продолжайте нажимать кнопку «Далее», пока не дойдете до окна, в котором можно выбрать дату восстановления.
- Подтвердите восстановление, выполнив оставшиеся шаги. После этого перезагрузите компьютер в обычном режиме.
Восстановить при загрузке
- Перезагрузите компьютер и нажмите F11, чтобы начать восстановление системы.
- Вы увидите экран «Дополнительные параметры», на котором вы найдете пункт «Восстановление системы».
- Вам будет предложено выбрать учетную запись администратора, просто выберите и войдите в свою учетную запись администратора.
- Нажимайте кнопку «Далее», пока не дойдете до экрана, на котором можно выбрать даты восстановления.
- Нажимайте кнопку «Далее», пока не дойдете до конца процесса восстановления и не увидите кнопку «Готово».
- Перезагрузите компьютер в обычном режиме.
Восстановление в Windows 10:
Внутри окна
- Запустите восстановление системы, введя его в поле поиска. Щелкните элемент, который появится в результатах поиска.
- Когда откроется окно «Восстановление системы», нажимайте «Далее», пока не получите список для выбора даты восстановления, выберите ту, которая, как вы знаете, лучше всего подходит для вас.
- Подтвердите процесс, нажав «Далее», затем «Да» и, наконец, «Готово». После закрытия окна перезагрузите компьютер.
Использование установочного носителя
- Если вы не можете загрузиться в Windows, вам лучше загрузить файл Media Creator из Microsoft. Создайте загрузочный диск с помощью DVD или флэш-диска.
- После этого перезагрузите компьютер и войдите в BIOS, чтобы изменить загрузочное устройство на DVD или флэш-диск.
- Когда вы перейдете к экрану установки, выберите «Устранение неполадок»> «Дополнительные параметры»> «Восстановление системы» и выполните процесс таким же образом.
Метод 2 — Исправить неправильную системную дату и время
Иногда Windows может работать неправильно из-за неправильной настройки времени. Чтобы установить время и дату:
В Windows 7
- Нажмите «Пуск», затем «Панель управления».
- Нажмите «Дата и время».
- В окне «Дата и время» нажмите «Изменить часовой пояс», чтобы выбрать правильный часовой пояс.
- Нажмите «Применить» и «ОК».
В Windows 8
- Откройте «Настройки», переместив указатель мыши вправо, при открытии вкладки щелкните значок шестеренки.
- Откроется новая всплывающая вкладка «Настройки», нажмите «Панель управления».
- На панели управления нажмите «Часы, язык и регион». Затем нажмите «Установить время и дату» в разделе «Дата и время».
- Когда откроется окно «Дата и время», нажмите «Изменить дату и время» и перейдите к нужной дате и времени в следующем окне. Чтобы подать заявку, просто нажмите «ОК».
В Windows 10
- Просто щелкните правой кнопкой мыши дату и время на панели задач, расположенной в правой нижней части экрана.
- Нажмите «Настроить дату и время». Откроются настройки даты и времени.
- Вы можете выбрать часовой пояс, а затем закрыть окно. Это автоматически обновит время и дату на панели задач.
Метод 3 — Проверьте отсутствие или повреждение файлов
- Запустить проверку системных файлов
- Чтобы запустить команду, откройте командную строку с повышенными привилегиями, набрав ее в окне поиска, затем щелкните правой кнопкой мыши командную строку и выберите «Запуск от имени администратора».
- Введите в командной строке sfc / scannow и дождитесь успешного завершения процесса проверки.
- Запустите Checkdisk — Chkdsk исправляет многие несоответствия с ОС. Системные ошибки также можно исправить с помощью этой утилиты. Чтобы запустить это,
- Откройте командную строку, введя ее в поле поиска, а затем, когда вы увидите результат в верхней части списка, щелкните его правой кнопкой мыши и выберите «Запуск от имени администратора».
- Ваша система может сказать, что вы не можете запустить ее в данный момент, потому что вы все еще обрабатываете данные, и спросит вас, хотите ли вы запустить ее перед следующим запуском, просто нажмите y для подтверждения, а затем выйдите с экрана и перезагрузите компьютер.
- После перезагрузки компьютера вы увидите, что checkdisk работает вне Windows, просто дайте ему закончить, пока он не даст вам отчет о том, что было найдено, исправлено или отмечено.
- Закройте окно и дайте компьютеру нормально перезагрузиться.
Другие языки:
How to fix C0000374 (Error C0000374) —
Wie beheben C0000374 (Fehler C0000374) —
Come fissare C0000374 (Errore C0000374) —
Hoe maak je C0000374 (Fout C0000374) —
Comment réparer C0000374 (Erreur C0000374) —
어떻게 고치는 지 C0000374 (오류 C0000374) —
Como corrigir o C0000374 (Erro C0000374) —
Hur man åtgärdar C0000374 (Fel C0000374) —
Jak naprawić C0000374 (Błąd C0000374) —
Cómo arreglar C0000374 (Error C0000374) —
Об авторе: Фил Харт является участником сообщества Microsoft с 2010 года. С текущим количеством баллов более 100 000 он внес более 3000 ответов на форумах Microsoft Support и создал почти 200 новых справочных статей в Technet Wiki.
Следуйте за нами:
Этот инструмент восстановления может устранить такие распространенные проблемы компьютера, как синие экраны, сбои и замораживание, отсутствующие DLL-файлы, а также устранить повреждения от вредоносных программ/вирусов и многое другое путем замены поврежденных и отсутствующих системных файлов.
ШАГ 1:
Нажмите здесь, чтобы скачать и установите средство восстановления Windows.
ШАГ 2:
Нажмите на Start Scan и позвольте ему проанализировать ваше устройство.
ШАГ 3:
Нажмите на Repair All, чтобы устранить все обнаруженные проблемы.
СКАЧАТЬ СЕЙЧАС
Совместимость
Требования
1 Ghz CPU, 512 MB RAM, 40 GB HDD
Эта загрузка предлагает неограниченное бесплатное сканирование ПК с Windows. Полное восстановление системы начинается от $19,95.
ID статьи: ACX014412RU
Применяется к: Windows 10, Windows 8.1, Windows 7, Windows Vista, Windows XP, Windows 2000
Совет по увеличению скорости #47
Оптимизируйте Windows с помощью средства устранения неполадок производительности:
Оптимизируйте свой компьютер с Windows 7 и Windows 10 с помощью средства устранения неполадок производительности для повышения скорости работы. Этот инструмент может находить проблемы и предлагать действенные решения по их устранению. Просто введите «средство устранения неполадок» в поле поиска на панели управления.
Нажмите здесь, чтобы узнать о другом способе ускорения работы ПК под управлением Windows
Содержание
- Critical error detected c0000374 qt
- Critical error detected c0000374 — C++ dll returns pointer off allocated memory to C#
- 4 Answers 4
- Critical error detected c0000374 while freeing the loaded dll by FreeLibrary
- Background
- User-defined DLL
- Problem
- Thread: Critical error detected c0000374 — on close MainWindow
- Critical error detected c0000374 — on close MainWindow
- Re: Critical error detected c0000374 — on close MainWindow
- Re: Critical error detected c0000374 — on close MainWindow
- Re: Critical error detected c0000374 — on close MainWindow
- How to fix the Runtime Code C0000374 Critical Error Detected c0000374
Critical error detected c0000374 qt
My program is getting a segmentation fault (SIGSEGV signal from Windows 7) while reading a file. The file is an ASCII file with 8380232 lines of text (238 MBytes in size). Each line of text consists of two real numbers seperated by a space. The code below basicially reads and parses each line, converts the strings to doubles and stores the double values in two arrays. I’m stepping through the code with a debugger and all seems well. So, I hit continue and at line 564 (two out of three times, other time it bombed at line 3) of the input text file I get this signal/error. I looked at the data file and nothing unusual is happening there. The code is below along with what was in the compile output window. Does anyone have any knowledge of what might be happening to cause this?
@
Debugging starts
Critical error detected c0000374
(Internal error: pc 0x1 in read in psymtab, but not in symtab.)
(Internal error: pc 0x1 in read in psymtab, but not in symtab.)
(Internal error: pc 0x1 in read in psymtab, but not in symtab.)
(Internal error: pc 0x1 in read in psymtab, but not in symtab.)
(Internal error: pc 0x0 in read in psymtab, but not in symtab.)
(Internal error: pc 0x1 in read in psymtab, but not in symtab.)
(Internal error: pc 0x1 in read in psymtab, but not in symtab.)
(Internal error: pc 0x1 in read in psymtab, but not in symtab.)
(Internal error: pc 0x1 in read in psymtab, but not in symtab.)
(Internal error: pc 0x0 in read in psymtab, but not in symtab.)
Debugging has finished
Debugging starts
Debugging has finished
@
Why not use a QVector or QList for the ch1_testvector and use ::append? Maybe your count exceeds the bounds of those arrays.
Thanks for replying. I’ll look into QVector and QLIst. I’m new to QT. I’ve sort of grown accustomed to and spoiled by .net/managed code, C++/CLI and C#. I stare at my C++ code here and often don’t even see memory bounds issues since I rarely have to concern myself with these things with a memory manager and managed pointers in the Microsoft world.
Well, meanwhile here’s my array declarations and instantiations. There should be enough room for the data.
@
double* ch1_testvector;
double* ch2_testvector;
.
.
.
ch1_testvector = new double [8388608];
ch2_testvector = new double [8388608];
.
.
.
@
By the way, I think I figured out what was happening. I don’t think my class was getting instantiated. I didn’t know non-static funcitons of a class would even begin to run without the class being instantiated.
Hi, indeed as mentioned before it is a good idea to use Qt storage classes. Then you don’t have to think about clearing memory when done with the data. In your case you should! When it is just double you need you can use the QList myList and append any new ones. This is also valid for pointers (QList myList).
Happy coding!
When you use the debugger always check for pointer to an object before you are calling some method using that pointer.
And also always use RAII idiom. It helps a lot.
Источник
Critical error detected c0000374 — C++ dll returns pointer off allocated memory to C#
I have a c++ dll which serving some functionality to my main c# application. Here i try to read a file, load it to memory and then return some information such as the Pointer to loaded data and count of memory blocks to c#. The Dll reads file to memory successfully but on the return to the main application, program crashes due to Heap Corruption(Critical error detected c0000374).
The code is quite simple and straightforward and I have done some similar things before with no problem, However i could not figure out what makes the problem here, I tried to allocate memory using «new, malloc and GlobalAlloc» but neither did help. Codes are as follow:
The program crashes on both debug and release mode. Unless I pause the program in debug mode after loading the file and call some blocks of memory in the «Visual Studio’s Immediate window». The size of files to be loaded are around 64MB and we have more than 2GB unused ram on the PC.
UPDATE: I noticed that, some third party programs which they working before, crash with «Exception Code: c0000005», and some other weird things happens in Windows 7 (the Host). so I tested the code in another installation of windows and everything seems to work as they should. So probably it’s related be the Windows 7. Now how could I fix the problem? «sfc /scannow» failed to find any issue.
4 Answers 4
If all your code is indeed what is shown above, then I don’t see the problem. However, when I get this issue, sometimes its because malloc/new/whatever detects heap corruption, often this corruption has already occurred previously in the program, but the crash has been delayed until the next call to new/malloc.
If you read other files, or allocate or free other buffers before the above is executed and crashes, I would look there for problems. Perhaps throw a bunch of asserts anywhere you write to buffers and check the bounds and what you are writing for overruns. Sorry this isn’t a concrete answer, I do not have enough rep to leave this advice as a comment.
I’m late to the party but here I go.
I received this error code from my own program, which brought me to this post. I was setting an array position out of range, causing the next allocation to crash the program, in Windows 7. I found the error by compiling with the -g flag with gcc from MinGW and then running the program with gdb. Somewhere here you read or write an invalid location and the next allocation picks up on the heap corruption. I solved my problem by bounds checking my iterators, but that doesn’t seem to be the problem here.
Main Problems with the C Program:
- The method you are using to find the size of the file is alright, however when you allocate memory for the Data array you are casting to a 32 bit integer array, which has problems. Casting to this requires that the size of the file in bytes be some multiple of 4. If you were to have a file with FILE_SIZE % 4 == 1 then there are 3 bytes which are not part of your allocated data, but are accessed when you look at the final element of the u32 array.
- How fread is implemented, you should be protected from writing to this out of range position, however you will miss the last 1 to 3 characters when the file size is not a multiple of 4 since integer division truncates remainders.
- You should close the file before exiting the scope, including after reading everything in the file.
- A solution to this is may be to round up the array size to the nearest multiple of 4. You are then guaranteed to not access out of range positions from [0] to [fSize — 1].
- If trying to copy past the last byte of the file causes a fatal error I don’t have a decent solution besides using character arrays rounded up the nearest multiple of 4, then reading byte for byte. After reading everything you can then cast to u32 since C is permissive with casting.
That version of software may have been doing some extra work when casting so that it wrote to a location out of range, or C# made some extra allocation calls that would do the same (I am not familiar with how C# compiles and what instruction changes it may impose).
Some code for finding the next multiple of 4:
Источник
Critical error detected c0000374 while freeing the loaded dll by FreeLibrary
I have met a memory error when I try to free an user-defined DLL. If you do not want to know the background of this problem, I recommend you to read my problem from the beginning of the section 2. user-defined DLL.
Background
In my program, I need to use a third-party library. In the following part I call it LIB-A / DLL-A . The abstract process of this library could be descripted by using 4 functions:
The used LIB-A has referred ice34d.dll , and iceutil34d.dll . By adding the lib and included files in my project (I call this program exe-A ), I have found these functions could work well.
But now I have to use another method to refer the DLL-A . In other words, I have to use LoadLibrary , GetProcAddress and FreeLibrary to complete this task. Since I have found that the DLL-A does not provide any avaliable interface of the above functions, I try to remove DLL-A from the folder containing exe-A . The result shows that DLL-A is not a valid file, exe-A could work well without it.
User-defined DLL
Because the DLL-A is invalid, I have to write a user-defined DLL to wrap the above 4 functions, I call this program DLL-B . DLL-B has be linked with such libs:
Although DLL-A is invalid, LIB-A is necessary, because I infer that the above 4 founctions are not only declared but also defined in LIB-A , and DLL-A is actually empty. After setting the libs and included files, I write 4 wrapping functions. Here are the main part of .h file and .cpp file.
.h file: (some parameters are omitted)
Problem
After all, I begin to write a test program (I call it exe-B ). In this program, I use such codes to load DLL-B :
It is confusing that even the program could be compiled well, GetLastError() returns 0, and all of the 4 founctions are performed well. However, once I let the program free the DLL instance, I would receive such an error:
If I do not free the library, there will be no error in this program.
To prove my guess, I have done another 2 experiments:
I write a DLL( DLL-C ) to wrap another library ( LIB-D ) designed by myself. And I load DLL-C by similiar method in the section. Problem. The result shows that DLL-C could be freed without error. The only difference between DLL-C and DLL-B is that DLL-B load the third-party libs( ice , LIB-A ), and DLL-C load a simple library ( LIB-D ) designed by myself. It seems that this error is triggered by the third-party libs. Unfortunately, I could not see the detail of these external libs.
I change the .cpp file as follow:
It is appalling that although I do nothing with the loaded DLL-B , once I load it, I could not free it safely. The error is the same as above error in section. Problem.
How could I solve this problem? Whether does it mean that I could not free the library but use it normally?
Источник
Thread: Critical error detected c0000374 — on close MainWindow
Thread Tools
Search Thread
Display
Critical error detected c0000374 — on close MainWindow
When i try to test the code, the program do the job, only at quit (by pressing X on the MainWindow) i have this issue:
in the «Application Ouput» window is write the current message «Critical error detected c0000374» and the debugger enter in editobject.h file with the yellow arrow at line 6;
what wrong i do?
Re: Critical error detected c0000374 — on close MainWindow
And did you ask Google what this error message means? This hit seems like it might be particularly relevant. (Not the specific error the poster experienced, but what the error means). And no, it isn’t a bug in Qt.
Hint: Look at how you have declared your QWidget-based variables in MainWindow.h. Why do all other Qt applications create child windows on the heap and not the stack (as your code does)? And how do you think that might result in memory corruption when your MainWindow is closed (and deleted)?
Last edited by d_stranz; 21st October 2020 at 21:47 .
Re: Critical error detected c0000374 — on close MainWindow
I try to answer:
1a) In Qt app is better to create child window or object on the heap because on close window or delete parent object all childs are deleted.
1a) On the stack is better to store small size data object and with contest access (like functions or slots), in the heap large size data object and without constest access.
2a) Like i read «Whether or not the variables are on the heap or stack depends upon how the object is allocated. So all members of the class will be allocated how the object is allocated.» in https://forum.qt.io/topic/108617/cla. -stack-or-heap so: MainWindow is allocated on the stack, like in my code glWidgetWindow+built_sphere_window+built_cylinder_ window+and so on (from Mainwindow.h) are allocated on the stack, what it is happen is an overflow of the stack?
2b)I’m confused about :
Re: Critical error detected c0000374 — on close MainWindow
OK, I will explain. The reason your code is crashing is because you have declared your member variable widgets directly, as QWidget instances, rather than as pointers to QWidget instances. Memory is being corrupted in the MainWindow destructor because the member variables are destroyed by C++ before the MainWindow instance is destroyed. However, because in Qt, these child widgets are owned by the MainWindow, Qt is trying to destroy them a second time (through the Qt parent-child relationship, which is responsible for destroying them), after C++ has already destroyed them. The memory they used to occupy is gone, and so you get a crash because Qt is trying to access an object that no longer exists. (It could be happening the other way around — Qt destroys them first, and then C++ tries to do it again, but it’s the same effect).
This has nothing to do with arguments about whether it is better to use heap vs. stack in any particular situation. It is entirely about Qt’s parent-child ownership hierarchy of QObjects and who is in charge of the child objects’ lifetimes.
So the solution to your problem is pretty simple:
1. Change every one of your QWidget-based member variables in MainWindow to «QWidget *».
2. In the constructor for MainWindow, call the «new» operator to create the QWidget instances
3. Use these widgets through the pointer operator (->)
In general, you should never declare QWidget-based member variables as QWidget, but always as QWidget *. (Actually, anything QObject-based).
The only places you should use QWidget directly are these (and maybe a few other similar cases):
1. In a method where the QWidget is in scope only for the life of the method, such as posting a dialog to get information from the user.
2. For MainWindow in main.cpp:
In both of these cases, the QObject instances are completely contained within the scope of the method so it is safe to create them on the stack.
Источник
How to fix the Runtime Code C0000374 Critical Error Detected c0000374
This article features error number Code C0000374, commonly known as Critical Error Detected c0000374 described as Manga Studio crashes with Error Code c0000374.
Error Information
Error name: Critical Error Detected c0000374
Error number: Code C0000374
Description: Manga Studio crashes with Error Code c0000374.
Software: Manga Studio
Developer: Celsys
This repair tool can fix common computer errors like BSODs, system freezes and crashes. It can replace missing operating system files and DLLs, remove malware and fix the damage caused by it, as well as optimize your PC for maximum performance.
About Runtime Code C0000374
Runtime Code C0000374 happens when Manga Studio fails or crashes whilst it’s running, hence its name. It doesn’t necessarily mean that the code was corrupt in some way, but just that it did not work during its run-time. This kind of error will appear as an annoying notification on your screen unless handled and corrected. Here are symptoms, causes and ways to troubleshoot the problem.
Definitions (Beta)
Here we list some definitions for the words contained in your error, in an attempt to help you understand your problem. This is a work in progress, so sometimes we might define the word incorrectly, so feel free to skip this section!
- Error code — An error code is a value returned to provide context on why an error occurred
- Crashes — A crash is the result of an unrecoverable error that causes the program to stop completely.
Symptoms of Code C0000374 — Critical Error Detected c0000374
Runtime errors happen without warning. The error message can come up the screen anytime Manga Studio is run. In fact, the error message or some other dialogue box can come up again and again if not addressed early on.
There may be instances of files deletion or new files appearing. Though this symptom is largely due to virus infection, it can be attributed as a symptom for runtime error, as virus infection is one of the causes for runtime error. User may also experience a sudden drop in internet connection speed, yet again, this is not always the case.
(Critical Error Detected c0000374) Repair Tool»/>
(For illustrative purposes only)
Causes of Critical Error Detected c0000374 — Code C0000374
During software design, programmers code anticipating the occurrence of errors. However, there are no perfect designs, as errors can be expected even with the best program design. Glitches can happen during runtime if a certain error is not experienced and addressed during design and testing.
Runtime errors are generally caused by incompatible programs running at the same time. It may also occur because of memory problem, a bad graphics driver or virus infection. Whatever the case may be, the problem must be resolved immediately to avoid further problems. Here are ways to remedy the error.
Repair Methods
Runtime errors may be annoying and persistent, but it is not totally hopeless, repairs are available. Here are ways to do it.
If a repair method works for you, please click the upvote button to the left of the answer, this will let other users know which repair method is currently working the best.
Источник
Номер ошибки: | Ошибка C0000374 | |
Название ошибки: | Critical Error Detected c0000374 | |
Описание ошибки: | Manga Studio crashes with Error Code c0000374. | |
Разработчик: | Celsys | |
Программное обеспечение: | Manga Studio | |
Относится к: | Windows XP, Vista, 7, 8, 10, 11 |
Проверка «Critical Error Detected c0000374»
«Critical Error Detected c0000374» обычно называется формой «ошибки времени выполнения». Чтобы убедиться, что функциональность и операции работают в пригодном для использования состоянии, разработчики программного обеспечения, такие как Celsys, выполняют отладку перед выпусками программного обеспечения. К сожалению, многие ошибки могут быть пропущены, что приводит к проблемам, таким как те, с ошибкой C0000374.
Ошибка C0000374 может столкнуться с пользователями Manga Studio, если они регулярно используют программу, также рассматривается как «Manga Studio crashes with Error Code c0000374.». В случае обнаруженной ошибки C0000374 клиенты могут сообщить о наличии проблемы Celsys по электронной почте или сообщать об ошибках. Celsys может устранить обнаруженные проблемы, а затем загрузить измененный файл исходного кода, позволяя пользователям обновлять свою версию. Таким образом, в этих случаях разработчик выпустит обновление программы Manga Studio, чтобы исправить отображаемое сообщение об ошибке (и другие сообщенные проблемы).
Почему возникает ошибка времени выполнения C0000374?
Сбой во время запуска Manga Studio или во время выполнения, как правило, когда вы столкнетесь с «Critical Error Detected c0000374». Причины сбоев обработки можно отличить, классифицируя ошибки C0000374 следующим образом:.
Ошибка C0000374 Crash — это типичная ошибка «Critical Error Detected c0000374», которая приводит к полному завершению работы программы. Как правило, это результат того, что Manga Studio не понимает входные данные или не знает, что выводить в ответ.
Утечка памяти «Critical Error Detected c0000374» — этот тип утечки памяти приводит к тому, что Manga Studio продолжает использовать растущие объемы памяти, снижая общую производительность системы. Критическими проблемами, связанными с этим, могут быть отсутствие девыделения памяти или подключение к плохому коду, такому как бесконечные циклы.
Ошибка C0000374 Logic Error — логическая ошибка Manga Studio возникает, когда она производит неправильный вывод, несмотря на то, что пользователь предоставляет правильный ввод. Это видно, когда исходный код Celsys включает дефект в анализе входных данных.
Celsys проблемы с Critical Error Detected c0000374 чаще всего связаны с повреждением или отсутствием файла Manga Studio. Как правило, решить проблему позволяет получение новой копии файла Celsys, которая не содержит вирусов. Помимо прочего, в качестве общей меры по профилактике и очистке мы рекомендуем использовать очиститель реестра для очистки любых недопустимых записей файлов, расширений файлов Celsys или разделов реестра, что позволит предотвратить появление связанных с ними сообщений об ошибках.
Ошибки Critical Error Detected c0000374
Частичный список ошибок Critical Error Detected c0000374 Manga Studio:
- «Ошибка программного обеспечения Critical Error Detected c0000374. «
- «Недопустимая программа Win32: Critical Error Detected c0000374»
- «Возникла ошибка в приложении Critical Error Detected c0000374. Приложение будет закрыто. Приносим извинения за неудобства.»
- «К сожалению, мы не можем найти Critical Error Detected c0000374. «
- «Critical Error Detected c0000374 не найден.»
- «Ошибка запуска программы: Critical Error Detected c0000374.»
- «Не удается запустить Critical Error Detected c0000374. «
- «Отказ Critical Error Detected c0000374.»
- «Ошибка пути программного обеспечения: Critical Error Detected c0000374. «
Проблемы Manga Studio Critical Error Detected c0000374 возникают при установке, во время работы программного обеспечения, связанного с Critical Error Detected c0000374, во время завершения работы или запуска или менее вероятно во время обновления операционной системы. Отслеживание того, когда и где возникает ошибка Critical Error Detected c0000374, является важной информацией при устранении проблемы.
Причины проблем Critical Error Detected c0000374
Эти проблемы Critical Error Detected c0000374 создаются отсутствующими или поврежденными файлами Critical Error Detected c0000374, недопустимыми записями реестра Manga Studio или вредоносным программным обеспечением.
В первую очередь, проблемы Critical Error Detected c0000374 создаются:
- Поврежденная или недопустимая запись реестра Critical Error Detected c0000374.
- Загрязненный вирусом и поврежденный Critical Error Detected c0000374.
- Другая программа (не связанная с Manga Studio) удалила Critical Error Detected c0000374 злонамеренно или по ошибке.
- Другое программное обеспечение, конфликтующее с Manga Studio, Critical Error Detected c0000374 или общими ссылками.
- Поврежденная загрузка или неполная установка программного обеспечения Manga Studio.
Продукт Solvusoft
Загрузка
WinThruster 2022 — Проверьте свой компьютер на наличие ошибок.
Совместима с Windows 2000, XP, Vista, 7, 8, 10 и 11
Установить необязательные продукты — WinThruster (Solvusoft) | Лицензия | Политика защиты личных сведений | Условия | Удаление
I have met a memory error when I try to free an user-defined DLL. If you do not want to know the background of this problem, I recommend you to read my problem from the beginning of the section 2. user-defined DLL.
Background
In my program, I need to use a third-party library. In the following part I call it LIB-A
/ DLL-A
. The abstract process of this library could be descripted by using 4 functions:
initResources(): initialze the configuration.
callAPI_to_saveAsFile(...): main process.
freeMem(...): free memory of returned data.
destroyResources(): free memory of the configuration.
The used LIB-A
has referred ice34d.dll
, and iceutil34d.dll
. By adding the lib and included files in my project (I call this program exe-A
), I have found these functions could work well.
But now I have to use another method to refer the DLL-A
. In other words, I have to use LoadLibrary
, GetProcAddress
and FreeLibrary
to complete this task. Since I have found that the DLL-A
does not provide any avaliable interface of the above functions, I try to remove DLL-A
from the folder containing exe-A
. The result shows that DLL-A
is not a valid file, exe-A
could work well without it.
User-defined DLL
Because the DLL-A
is invalid, I have to write a user-defined DLL to wrap the above 4 functions, I call this program DLL-B
. DLL-B
has be linked with such libs:
iced.lib
iceutild.lib
LIB-A
Although DLL-A
is invalid, LIB-A
is necessary, because I infer that the above 4 founctions are not only declared but also defined in LIB-A
, and DLL-A
is actually empty. After setting the libs and included files, I write 4 wrapping functions. Here are the main part of .h file and .cpp file.
.h file: (some parameters are omitted)
#include "LIBA.h"
#ifdef MYLIBDLL
#define CM_EXTERN extern "C" _declspec(dllimport)
#else
#define CM_EXTERN extern "C" _declspec(dllexport)
#endif
CM_EXTERN int w_initResources();
CM_EXTERN int w_callAPI_to_saveAsFile(...);
CM_EXTERN int w_destroyResources();
CM_EXTERN int w_freeMem(...);
.cpp file:
#include "stdafx.h"
#pragma comment (lib, "../music-lib/release_dll/iced.lib")
#pragma comment (lib, "../music-lib/release_dll/iceutild.lib")
#pragma comment (lib, "../music-lib/release_dll/DLLA.lib")
int w_initResources(){
return initResources();
}
int w_destroyResources(){
return destroyResources();
}
int w_freeMem(...){
return freeMem(...);
}
int w_callAPI_to_saveAsFile(...){
return callAPI_to_saveAsFile(...);
}
char* w_callAPI_to_downFileByte(char* fileURL,char *ret_bytes){
return callAPI_to_downFileByte(fileURL, ret_bytes);
}
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
Problem
After all, I begin to write a test program (I call it exe-B
). In this program, I use such codes to load DLL-B
:
.h file:
typedef int (*callAPI_to_saveAsFile_ptr)(...);
typedef int (*initResources_ptr)();
typedef int (*destroyResources_ptr)();
typedef int (*freeMem_ptr)(...);
.cpp file:
callAPI_to_saveAsFile_ptr Proc_API = NULL;
initResources_ptr init_API = NULL;
destroyResources_ptr destru_API = NULL;
freeMem_ptr free_API = NULL;
HINSTANCE h = LoadLibraryA("DLLB.dll");
cout << "ERROR:" << GetLastError() << endl;
if (h){
Proc_API = (callAPI_to_saveAsFile_ptr)GetProcAddress(h, "w_callAPI_to_saveAsFile");
init_API = (initResources_ptr)GetProcAddress(h, "w_initResources");
destru_API = (destroyResources_ptr)GetProcAddress(h, "w_destroyResources");
free_API = (freeMem_ptr)GetProcAddress(h, "w_freeMem");
cout << "Have loaded: " << "DLLB.dll" << " successfully!" << endl;
}
else{
cout << "Do not find this DLL:" << "DLLB.dll" << endl;
FreeLibrary(h);
return 0x100;
}
int errorflag=0;
if (Proc_API==NULL){
cout << "Function not loaded: callAPI_to_saveAsFile" << endl;
errorflag = errorflag | 0x001;
}
if (init_API==NULL){
cout << "Function not loaded: initResources" << endl;
errorflag = errorflag | 0x002;
}
if (destru_API==NULL){
cout << "Function not loaded: destroyResources" << endl;
errorflag = errorflag | 0x004;
}
if (CMISS_free_API==NULL){
cout << "Function not loaded: freeMem" << endl;
errorflag = errorflag | 0x008;
}
if (errorflag!=0){
FreeLibrary(h);
return 0x100 | errorflag;
}
cout << "Function loaded successfully!" << endl;
...Perform above functions...
if(h)
FreeLibrary(h);
return 0;
It is confusing that even the program could be compiled well, GetLastError() returns 0, and all of the 4 founctions are performed well. However, once I let the program free the DLL instance, I would receive such an error:
Critical error detected c0000374
exeB.exe has triggered a breakpoint.
If I do not free the library, there will be no error in this program.
To prove my guess, I have done another 2 experiments:
Exp1
I write a DLL(DLL-C
) to wrap another library (LIB-D
) designed by myself. And I load DLL-C
by similiar method in the section. Problem. The result shows that DLL-C
could be freed without error. The only difference between DLL-C and DLL-B is that DLL-B load the third-party libs(ice
, LIB-A
), and DLL-C load a simple library (LIB-D
) designed by myself. It seems that this error is triggered by the third-party libs. Unfortunately, I could not see the detail of these external libs.
Exp2
I change the .cpp file as follow:
HINSTANCE h = LoadLibraryA("DLLB.dll");
cout << "ERROR:" << GetLastError() << endl;
if (h){
cout << "H_Valid!" << endl;
FreeLibrary(h);
cout << "Have loaded: " << "DLLB.dll" << " successfully and free it!" << endl;
return 0;
}
else{
cout << "Do not find this DLL:" << "DLLB.dll" << endl;
FreeLibrary(h);
return 0x100;
}
It is appalling that although I do nothing with the loaded DLL-B
, once I load it, I could not free it safely. The error is the same as above error in section. Problem.
Critical error detected c0000374
exeB.exe has triggered a breakpoint.
How could I solve this problem? Whether does it mean that I could not free the library but use it normally?
I have met a memory error when I try to free an user-defined DLL. If you do not want to know the background of this problem, I recommend you to read my problem from the beginning of the section 2. user-defined DLL.
Background
In my program, I need to use a third-party library. In the following part I call it LIB-A
/ DLL-A
. The abstract process of this library could be descripted by using 4 functions:
initResources(): initialze the configuration.
callAPI_to_saveAsFile(...): main process.
freeMem(...): free memory of returned data.
destroyResources(): free memory of the configuration.
The used LIB-A
has referred ice34d.dll
, and iceutil34d.dll
. By adding the lib and included files in my project (I call this program exe-A
), I have found these functions could work well.
But now I have to use another method to refer the DLL-A
. In other words, I have to use LoadLibrary
, GetProcAddress
and FreeLibrary
to complete this task. Since I have found that the DLL-A
does not provide any avaliable interface of the above functions, I try to remove DLL-A
from the folder containing exe-A
. The result shows that DLL-A
is not a valid file, exe-A
could work well without it.
User-defined DLL
Because the DLL-A
is invalid, I have to write a user-defined DLL to wrap the above 4 functions, I call this program DLL-B
. DLL-B
has be linked with such libs:
iced.lib
iceutild.lib
LIB-A
Although DLL-A
is invalid, LIB-A
is necessary, because I infer that the above 4 founctions are not only declared but also defined in LIB-A
, and DLL-A
is actually empty. After setting the libs and included files, I write 4 wrapping functions. Here are the main part of .h file and .cpp file.
.h file: (some parameters are omitted)
#include "LIBA.h"
#ifdef MYLIBDLL
#define CM_EXTERN extern "C" _declspec(dllimport)
#else
#define CM_EXTERN extern "C" _declspec(dllexport)
#endif
CM_EXTERN int w_initResources();
CM_EXTERN int w_callAPI_to_saveAsFile(...);
CM_EXTERN int w_destroyResources();
CM_EXTERN int w_freeMem(...);
.cpp file:
#include "stdafx.h"
#pragma comment (lib, "../music-lib/release_dll/iced.lib")
#pragma comment (lib, "../music-lib/release_dll/iceutild.lib")
#pragma comment (lib, "../music-lib/release_dll/DLLA.lib")
int w_initResources(){
return initResources();
}
int w_destroyResources(){
return destroyResources();
}
int w_freeMem(...){
return freeMem(...);
}
int w_callAPI_to_saveAsFile(...){
return callAPI_to_saveAsFile(...);
}
char* w_callAPI_to_downFileByte(char* fileURL,char *ret_bytes){
return callAPI_to_downFileByte(fileURL, ret_bytes);
}
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
Problem
After all, I begin to write a test program (I call it exe-B
). In this program, I use such codes to load DLL-B
:
.h file:
typedef int (*callAPI_to_saveAsFile_ptr)(...);
typedef int (*initResources_ptr)();
typedef int (*destroyResources_ptr)();
typedef int (*freeMem_ptr)(...);
.cpp file:
callAPI_to_saveAsFile_ptr Proc_API = NULL;
initResources_ptr init_API = NULL;
destroyResources_ptr destru_API = NULL;
freeMem_ptr free_API = NULL;
HINSTANCE h = LoadLibraryA("DLLB.dll");
cout << "ERROR:" << GetLastError() << endl;
if (h){
Proc_API = (callAPI_to_saveAsFile_ptr)GetProcAddress(h, "w_callAPI_to_saveAsFile");
init_API = (initResources_ptr)GetProcAddress(h, "w_initResources");
destru_API = (destroyResources_ptr)GetProcAddress(h, "w_destroyResources");
free_API = (freeMem_ptr)GetProcAddress(h, "w_freeMem");
cout << "Have loaded: " << "DLLB.dll" << " successfully!" << endl;
}
else{
cout << "Do not find this DLL:" << "DLLB.dll" << endl;
FreeLibrary(h);
return 0x100;
}
int errorflag=0;
if (Proc_API==NULL){
cout << "Function not loaded: callAPI_to_saveAsFile" << endl;
errorflag = errorflag | 0x001;
}
if (init_API==NULL){
cout << "Function not loaded: initResources" << endl;
errorflag = errorflag | 0x002;
}
if (destru_API==NULL){
cout << "Function not loaded: destroyResources" << endl;
errorflag = errorflag | 0x004;
}
if (CMISS_free_API==NULL){
cout << "Function not loaded: freeMem" << endl;
errorflag = errorflag | 0x008;
}
if (errorflag!=0){
FreeLibrary(h);
return 0x100 | errorflag;
}
cout << "Function loaded successfully!" << endl;
...Perform above functions...
if(h)
FreeLibrary(h);
return 0;
It is confusing that even the program could be compiled well, GetLastError() returns 0, and all of the 4 founctions are performed well. However, once I let the program free the DLL instance, I would receive such an error:
Critical error detected c0000374
exeB.exe has triggered a breakpoint.
If I do not free the library, there will be no error in this program.
To prove my guess, I have done another 2 experiments:
Exp1
I write a DLL(DLL-C
) to wrap another library (LIB-D
) designed by myself. And I load DLL-C
by similiar method in the section. Problem. The result shows that DLL-C
could be freed without error. The only difference between DLL-C and DLL-B is that DLL-B load the third-party libs(ice
, LIB-A
), and DLL-C load a simple library (LIB-D
) designed by myself. It seems that this error is triggered by the third-party libs. Unfortunately, I could not see the detail of these external libs.
Exp2
I change the .cpp file as follow:
HINSTANCE h = LoadLibraryA("DLLB.dll");
cout << "ERROR:" << GetLastError() << endl;
if (h){
cout << "H_Valid!" << endl;
FreeLibrary(h);
cout << "Have loaded: " << "DLLB.dll" << " successfully and free it!" << endl;
return 0;
}
else{
cout << "Do not find this DLL:" << "DLLB.dll" << endl;
FreeLibrary(h);
return 0x100;
}
It is appalling that although I do nothing with the loaded DLL-B
, once I load it, I could not free it safely. The error is the same as above error in section. Problem.
Critical error detected c0000374
exeB.exe has triggered a breakpoint.
How could I solve this problem? Whether does it mean that I could not free the library but use it normally?
Phenomenon:
The specific scenario is detected in New allocated memory, and the VS output information is: Critical Error Detected C0000374 is normal on X64, X86 is crashed
This occurs when memory is allocated, but this is the kernel-mode address area, which the heap manager cannot specify. So it’s clear that the heap data has been tampered with by overflow, which is heap corruption. The next step is to find out where the data overflow is occurring.
Analysis:
Debug looks at the normal allocation of memory, generally this is caused by the array out of bounds.
If not this time, then probably the last time the memory assignment crossed the line, causing the heap to break.
Solutions:
Find the location of the last memory allocation in the code, add 1 to the length, normal. Problem solving.
Int Buflen = 100;
_PRTA(unsigned char,ScaleBuf,Buflen + 1); //
Here is the smart pointer used; Unsigned char (unsigned char) does not need to store the end char. In theory, it does not need to add 1.
Conclusion:
In this case, basically the memory assignment is out of bounds, so let’s see if this is the case in the code above;
1. Memory allocation is short 1, 2. Memory assignment is out of bounds and the length is over. Such as memset ();
Read More:
У меня есть c ++ dll, который обслуживает некоторые основные функции моего основного приложения на c #.
Здесь я пытаюсь прочитать файл, загрузить его в память и затем вернуть некоторую информацию, такую как указатель на загруженные данные и количество блоков памяти, на c #. Dll успешно читает файл в память, но по возвращении в основное приложение происходит сбой программы из-за повреждения кучи (обнаружена критическая ошибка c0000374).
Код довольно прост и понятен, и раньше я делал подобные вещи без проблем. Однако я не мог понять, в чем здесь проблема, я попытался выделить память, используя «new, malloc и GlobalAlloc», но ни одна из них не помогла. Коды следующие:
C ++ MyDll:
typedef unsigned long U32;
extern "C" __declspec(dllexport) int ReadFile(LPSTR Path, U32** DataPtr, U32* Count)
{
FILE *fp;
U32 *Data;
CString tempStr(Path);
long fSize;
if(!(fp = fopen(tempStr, "rb"))) {
return 0;
}
// Obtain File Size;
fseek(fp, 0, SEEK_END);
fSize = ftell(fp);
rewind(fp);
Data = (U32 *)GlobalAlloc(0, fSize);
if(Data == NULL) {
fclose(fp);
return -1;
}
// Copy file into the buffer.
if(!(*Count = fread(Data, sizeof(U32), fSize / sizeof(U32), fp))) {
fclose(fp);
free(Data);
return -2;
}
*DataPtr = (U32 *)Data;
return 1;
}
Приложение C #:
[DllImport(@"MyDll.dll", CallingConvention= CallingConvention.Cdecl)]
private static extern int ReadFile([MarshalAs(UnmanagedType.LPStr)]string Path, out IntPtr dataPtr, out uint Count);
private void readDump(string Path)
{
uint count = 0;
IntPtr Data = new IntPtr();
try{
if(ReadFile(Path, out Data, out count) == 1) //The Program crashes just right after this statement
{
//Do Something ...
}
}
catch() {}
}
Программа вылетает как в режиме отладки, так и в режиме выпуска. Если я не приостановлю программу в режиме отладки после загрузки файла и вызову несколько блоков памяти в «Немедленном окне Visual Studio».
Размер загружаемых файлов составляет около 64 МБ, и у нас более 2 ГБ неиспользуемой оперативной памяти на ПК.
ОБНОВИТЬ: Я заметил, что некоторые сторонние программы, с которыми они работали раньше, аварийно завершают работу с «Кодом исключения: c0000005», и некоторые другие странные вещи происходят в Windows 7 (хост). поэтому я проверил код в другой установке Windows, и все, кажется, работает, как они должны. Так что, вероятно, это связано с Windows 7. Теперь, как я мог решить проблему? «sfc / scannow» не смог найти ни одной проблемы.
6
Решение
Если весь ваш код действительно такой, как показано выше, то я не вижу проблемы. Однако, когда я получаю эту проблему, иногда потому, что malloc / new / независимо обнаруживает повреждение кучи, часто это повреждение уже происходило ранее в программе, но сбой откладывался до следующего вызова new / malloc.
Если вы читаете другие файлы или выделяете или освобождаете другие буферы до того, как вышеперечисленное будет выполнено и вылетит, я буду искать там проблемы. Возможно, бросьте кучу утверждений в любом месте, где вы пишете, в буферы и проверьте границы и то, что вы пишете для переполнения.
Извините, это не конкретный ответ, мне не хватает представителя, чтобы оставить этот совет в качестве комментария.
20
Другие решения
Вы распределяете выходные данные 2 раза.
Однажды в C # как новый IntPtr
а затем в C ++ как GlobalAlloc
а затем вернуть указатель, возвращенный GlobalAlloc
, Таким образом, указатель вернулся новый intPtr
был потерян
1