Утечка памяти в Смешанном Режиме C++ / приложение CLR

RMDIR [/S] [/Q] [drive:]path

RD [/S] [/Q] [drive:]path

  • /S Удаляет все каталоги и файлы в указанном каталоге в дополнение к самому каталогу. Используемый для удаления дерева каталогов.

  • /Q режим Quiet, не спрашивайте, удалить ли хорошо дерево каталогов с /S

9
задан John 6 July 2009 в 21:27
поделиться

5 ответов

OK Наконец-то я нашел проблему.

Это было вызвано неправильной настройкой для /EH (Exception Handling).

В основном, при использовании .NET-приложений в смешанном режиме, вы должны убедиться, что все статически связанные либы скомпилированы с /EHa вместо /EHs по умолчанию.

(Само приложение также должно быть скомпилировано с помощью /EHa, но это дано - компилятор сообщит об ошибке, если вы его не используете . Проблема в том, что при компоновке в других статических родных библиотеках)

Проблема в том, что исключения, попавшие в управляемый бит приложения, которые были брошены в родные библиотеки, скомпилированные с /EHs, заканчиваются некорректной обработкой исключения. Деструкторы для объектов на Си++ в этом случае вызываются некорректно.

В моем случае это произошло только в редком месте, поэтому мне понадобились годы, чтобы это заметить.

6
ответ дан 4 December 2019 в 21:11
поделиться

У вас может быть утечка справочной информации, посмотрите программу профилирования ANTS. Ants Profiler

Эталонная утечка - это файл.

0
ответ дан 4 December 2019 в 21:11
поделиться

Попробуйте: DebugDiags .
После создания нескольких дампов памяти он даст вам хорошее резюме о том, какая память была выделена, и, в зависимости от обнаружения вашей PDB, может сказать вам, кем она была выделена.

0
ответ дан 4 December 2019 в 21:11
поделиться

Возможно ли, что вы пропустили некоторые утилиты, может случиться, если вы используете GDI + и многие другие API.

Если вы запустите инструмент статического анализа FXCop, у него есть правило, чтобы проверить, если вы используете GDI + и многие другие API. Вызывали операторы dispose (или использовали "using") для ваших объектов, которые предоставляют интерфейс. В .Net, если функция использует неуправляемый код, она обычно предоставляет вам метод удаления или закрытия, чтобы избежать утечки ресурса / памяти.

0
ответ дан 4 December 2019 в 21:11
поделиться

Like Spence was saying, but for C++/CLI ;)....

For any object which you are using in C++/CLI, if you create more that object's from you C++ code, you should try to use stack allocation seymantics, even though this is a compiler magic sort of thing, it is able to setup the nested __try {} __finally {} statements you may be used to using from native code (that is setup them in a way to not loose a call to Dispose).

Nish's article at the code project here on C++/CLI stack allocation semantics is pretty good and goes into depth about how to emulate using{}.

You should also make sure to delete any object's that implment IDisposable as you can not call Dispose in C++/CLI, delete does this for you, if your not using stack semantics..

I usually call Close myself on Streams and try to assign nullptr when I am finished with object's, just in case.

You may also want to check out this article on memory issues, perticularly about event subscribers, if you are assigning event's to your objects, you may be leaking...

As a last resort (or maybe first:), one thing I have done in the past is make use of the CLR profiler API, here's another article on how to do this, the author's writer (Jay Hilyard) has an example that answers;

  • Of each .NET type that is used, how многие экземпляры объектов выделено?
  • Насколько велики экземпляры каждого типа?
  • Какие уведомления предоставляет сборщик мусора, как он идет через сборку мусора и что ты можешь узнать?
  • Когда сборщик мусора collect the object instances?

Should get you a better idea than some commodity profiler, I've noticed that they can be occasionally misleading depending on your allocation porofile (btw. watch out for large object heap issues, > ~83kb objects are specially handled, in that case, I'd reccomend, getting out of the large object heap :).

Given your comments, a few more things...

I've posted before about image load's not charging quota or any other disernable statistic, what this means, you may need to track down some handle or loader issue (see loader lock eventually), but before that, you can try setting up some Constrained Execution Regions, they can work wonders, but are also unfortunately difficult to retro-fit into non-pure code.

This recent MSDN Mag, article document's a lot of perfmon type memory sperlunking (followup for this older one).

From the VS Perf Blog, they show how to use SOS in visual studio, which can be handy, to track down rouge DLL's, related posts are also good.

Maoni Stephen's Blog and company, he say's he's on the perf team, but essentially 100% of his posts are with respect to the GC so much so he may of well of wrote it.

Rick Byers is a dev with the CLR diagnostics team, many of his blog-buddies are also good source's, however, I would strongly suggest also refering to the quite new dev/diagnostics forum. They have recently expanded the scope of their discussions.

Code Coverage Tools and tracing can often help, to give you an overview of what's actually running.

(specically, those perticular stat's may not be giving you a global view of what is plauging your code, I can say that recently, I have found (even with .net4beta binaries, the profiler from this company, is quite good, it is capable of deriving native/managed leaks's from it's profile traces, brings you back to the exact source lines (even if optimized, quite nice (and it has a 30day trial)))).

Good luck!! Hope some of this helps, it's only fresh in my mind, as I am doing much of the same work right now ;)

4
ответ дан 4 December 2019 в 21:11
поделиться
Другие вопросы по тегам:

Похожие вопросы: