Dr memory как пользоваться

от admin

Dr. Memory as a Visual Studio Tool

Dr. Memory has support for running within the Visual Studio IDE as an External Tool. The Windows installer automatically creates a new Tools menu entry for launching Dr. Memory for each version of Visual Studio detected at install time. If you are using a local install, or if you installed Visual Studio after installing Dr. Memory, or if you are using Visual Studio Express 2010 and it was in Basic mode at the time you installed Dr. Memory, you will need to follow the following instructions in order to add Dr. Memory as an External Tool.

If using Visual Studio Express 2010, first enable the full menu system by selecting Tools | Settings | Expert Settings (this step is not necessary for Visual Studio Professional or later versions of Visual Studio Express).

Next, for Visual Studio 2005 through 2012, select the Tools | External Tools. menu option to open the External Tools dialog box. Click Add and fill in the fields as follows (adjusting the path to drmemory.exe if you installed it somewhere else):

Check the Use Output window checkbox. Click OK.

For Visual Studio 6, select Tools | Customize , then the Tools tab, and then click the New button. Fill in the fields as above, though the Title field is instead the input box in the main list. Also, you’ll want quotes around the TargetPath variable (but you do not want quotes for any later Visual Studio version):

Now you can select Tools | Dr. Memory and Visual Studio will run your application. The output of Dr. Memory (along with your program) will be printed to the Output Window. You can double-click on a source file on any callstack frame in order to automatically open up that file to the line number indicated.

To pass arguments to your application, in the External Tools dialog box entry for Dr. Memory, either directly add them for all runs, or check the «Prompt for arguments» checkbox to be prompted for arguments on each invocation. Add application arguments at the end, after the pre-filled-in string:

For Dr. Memory as an External Tool set up by the Dr. Memory installer, prompting for arguments is on by default.

Invoking Dr. Memory from the Command Line

Run your application as you normally would from a command prompt (on Windows, either the cmd shell or a Cygwin prompt), with drmemory and «—» prefixed to the command line (the «—» separates any arguments to Dr. Memory from the application being run).

On Linux, Mac, or an Android native application:

Examples throughout the rest of the documentation will use just one platform, but can readily be adapted to the other by changing the front-end ( drmemory.exe or drmemory ) and the path style.

If as part of Installing Dr. Memory you did not add Dr. Memory to your path, you’ll need to specify the full path to Dr. Memory.

On Windows, you can also drag-and-drop your application onto drmemory.exe in Windows Explorer or on the Desktop if you requested a Desktop shorcut upon installation.

For Java applications on Android, see the information under Preparing Your Application for Android.

When running scripts it is best to explicitly invoke the interpreter rather than invoking the script directly. For example:

Examining the Results

Dr. Memory’s results are written to a file called results.txt inside a subdirectory created for each invocation of Dr. Memory, inside Dr. Memory’s log directory. The log directory by default is the logs subdirectory of the unpacked installation, or the Dr. Memory directory inside your profile directory when Dr. Memory is installed into Program Files on Windows. It can be changed with the -logdir option:

When an application is executed under Dr. Memory’s control, it creates a subdirectory in the base log directory named «DrMemory-<appname>.<pid>.NNN», where NNN is a counter that is incremented to ensure unique names.

On Windows, the results files is automatically opened in notepad when the application exits. This only occurs for the top-level process; if it created child processes, they will be followed by Dr. Memory and have their own result directories and files, but these will not be automatically displayed. The option -batch can be used to disable the launch of notepad at application exit.

For full details on each type of error reported by Dr. Memory, see Error Types Reported by Dr. Memory.

If you would like to attach a debugger at the point an error is first detected, use the -pause_at_unaddressable or -pause_at_uninitialized options (see Dr. Memory Runtime Option Reference). Unfortunately, full debugger integration is not yet implemented, and the current PC and top few callstack frames are inside the Dr. Memory tool when attaching at the pause point. When using the Debugging Tools for Windows debugger, switching to a pure application context can be done using a script provided by DynamoRIO for 64-bit or for 32-bit to load the tool symbols. Once loaded, use the CONTEXT local variable provided by Dr. Memory in the drmemorylib!report_pause_at_error frame to swap to the application context via the debugger command «.cxr». This would look something like this from the windbg prompt:

Application Versus System Library Errors

Current versions of Dr. Memory can end up reporting uninitialized read and leak errors in system library code on large Windows applications. Future Dr. Memory versions will eliminate these errors, but for now these likely false positive errors are listed in a separate file from the normal results.txt called potential_errors.txt . The count of such errors is listed in the ERRORS IGNORED section of the main error summary. For example:

It is possible that some of these errors are in fact application errors in parameters passed to system library routines where those parameters are not used or read until deep into a system library callstack, though they are suspected of being false positives due to being reported in several layers of system library code. The pattern checking used to identify system libraries whose errors should be reported separately can be tuned via two features, a blocklist and an allowlist. Each feature contains patterns against which file paths are matched. These patterns can contain * or ? wildcards.

The allowlist takes precedence and if set the blocklist is ignored. The allowlist is empty by default. The option -lib_allowlist contains a ;-separated sequence of patterns against which library or executable paths are matched. The option -lib_allowlist_frames controls how many of the frames in each callstack, starting from the top frame, are examined. If an allowlist pattern appears in any one or more of those top frames, an error is reported normally. Otherwise, it is separated as a potential error. The expected usage model is to populate the allowlist with a list of paths in which application libraries or executables reside, to limit the error reports to those paths.

The blocklist is controlled by parallel options -lib_blocklist and -lib_blocklist_frames . Running with -lib_blocklist_frames 0 will disable the blocklist and report all errors as application errors in results.txt . When non-zero, it controls how many of the top frames must all match the blocklist before an error is separated as a potential error. I.e., there must be -lib_blocklist_frames frames in a row that match a blocklist entry (unlike the allowlist where only a single frame must match).. The blocklist is only enabled by default on Windows. There is a separate option -lib_blocklist_default which is appended to -lib_blocklist and whose default value matches libraries in $SYSTEMROOT and in the «Microsoft Shared» directories inside $CommonProgramFiles and $CommonProgramFiles(x86). This separate option is intended to not be set by users; instead, users set the -lib_blocklist option and so avoid affecting the default values.

An additional allowlist based on source file paths is available under the options -src_allowlist and -src_allowlist_frames . If combined with -lib_allowlist , the library-based allowlist acts first, with the source file-based allowlist filtering the errors that remain.

If many false positives are being reported and additional performance is desired at the risk of not detecting all application errors, Dr. Memory’s Light Mode can be used to disable checking for uninitialized reads and leaks.

Eliminating Uninitialized Read Checks By Library

Dr. Memory has an additional type of blocklist beyond the blocklist for system library errors described in Application Versus System Library Errors. This blocklist is controlled by the option -check_uninit_blocklist , which is a ,-separated list of library names. Unlike the other blocklist, these names are basenames and not whole paths, as they are meant to correspond to library names given in suppression files. For each library on this list, Dr. Memory will not report any uninitialized reads while directly executing the library’s code. This is a more efficient means to eliminate errors than using suppressions or the -lib_blocklist option, but it only applies to uninitialized reads.

Читать:
Ошибка 182 amd radeon что делать

When Dr. Memory sees a whole-module suppression – a suppression containing only a single frame of the form «name!*» – it automatically adds «name» to the -check_uninit_blocklist option list.

Controlling Child Processes

By default, Dr. Memory monitors all child processes. To disable this behavior and not monitor any children, use this option:

On Windows, to follow all children except certain applications, run this command with the executable name of each application you do not wish to monitor, prior to running Dr. Memory with default options:

Where «myapp» is the basename of your executable (i.e., the file name without any directories).

The drconfig.exe tool is in the same directory as drmemory.exe and is only available on Windows in the current release.

This -norun request is permanent and affects all subsequent Dr. Memory executions by the user that issued the -norun request. To undo it, use this command:

Applications That Do Not Exit

While Dr. Memory updates the results.txt file as the application runs, it does not perform leak checking or produce a summary of errors until the end of the run. For applications that do not have a normal exit, such as daemons, Dr. Memory provides a method of forcing end-of-run actions.

Run drmemory with the -nudge option and the process identifier of the application in order to request leak checking and other end-of-run actions:

Tuning for Performance

Dr. Memory’s default options are set up to find the most errors. Several key options can be adjusted to improve performance, at the cost of less information on each error report or even identification of fewer error types. Reducing -malloc_max_frames , disabling -delay_frees_stack , and disabling leak checking can improve performance on malloc-intensive applications. For more significant improvements, consider using Dr. Memory’s Light Mode.

  • Dr. Memory version 2.3.19327 — Fri Mar 10 2023 03:19:50

Dr memory как пользоваться

При написании программ, использующих динамическое выделение памяти (функции malloc, calloc, realloc, free ), необходимо помнить об освобождении всей когда-либо выделенной памяти. «Утечкой памяти» называется ситуация, когда программа по каким-либо причинам не освобождает память, которая больше не будет использоваться. Необходимо уметь обнаруживать подобные проблемы!

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

Microsoft Visual C Compiler / MS Windows

В начале вашей программы добавьте следующие строки (важно соблюдать порядок!)

и затем добавьте в конец вашей функции main вызов

Эта функция распечатает сообщение в Output window с информацией об утечках памяти, если таковые имеются.

Ниже показан пример такого сообщения

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

GNU Compiler Collection / Linux

В начале вашей программы добавьте следующую строку

и в самое начало функции main вызов

Затем просто запускаете вашу программу и после нее утилиту mtrace

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

GNU Compiler Collection (MinGW) / MS Windows

Модификаций исходного текста программы не требуется. Необходимо скомпилировать программу со следующими флагами:

Затем запустить вашу программу с помощью Dr. Memory:

Вывод содержит информацию о имеющихся проблемах при работе с динамической памятью, в частности об утечках памяти:

Также можно найти информацию об источнике утечки в исходном коде программы с указанием места в файле.

Действия

© Олег Дашевский со товарищи, 2010–2023. Сайт работает на платформе Coursette

Как использовать DrMemory для отображения и сообщения об утечке памяти в C ++?

Я специально создал приложение C ++ ниже, которое может иметь утечку памяти.

После создания этого приложения вместе со следующими параметрами (как указано в документации DrMemory) «-ggdb -static-libgcc -static-libstdc ++» , Я выполнил исполняемый файл с помощью drmemory.exe, например так:

drmemory.exe TestingDrMemory.exe

Тем не менее, я не вижу сообщений об ошибках / журналах, связанных с утечкой памяти, и я не могу определить строку в исходном коде, что это происходит. Возможно ли это в DrMemory? Как правильно использовать это для идентификации / обнаружения строк в исходном коде, которые вызывают утечку памяти?

Ловим утечки памяти в С/С++

Сегодня я хочу немного приоткрыть свет над тем, как бороться с утечкой памяти в Си или С++.

На Хабре уже существует две статьи, а именно: Боремся с утечками памяти (C++ CRT) и Утечки памяти в С++: Visual Leak Detector. Однако я считаю, что они недостаточно раскрыты, или данные способы могут не дать нужного вам результата, поэтому я хотел бы по возможности разобрать всем доступные способы, дабы облегчить вам жизнь.

Windows — разработка
Начнем с Windows, а именно разработка под Visual Studio, так как большинство начинающих программистов пишут именно под этой IDE.

Для понимания, что происходит, прикладываю реальный пример:

А также есть Student.h и Student.c в котором объявлены структуры и функции.

Есть задача: продемонстрировать отсутствие утечек памяти. Первое, что приходит в голову — это CRT. Тут все достаточно просто.

В начало файла, где находится main, необходимо добавить этот кусок кода:

А перед return 0 нужно прописать это: _CrtDumpMemoryLeaks(); .

В итоге, в режиме Debug, студия будет выводить это:

Супер! Теперь вы знаете, что у вас утечка памяти. Теперь нужно устранить это, поэтому необходимо просто узнать, где мы забываем очистить память. И вот тут возникает проблема: а где, собственно, выделялась эта память?

После того, как я повторил все шаги, я выяснил, что память теряется где-то здесь:

Но как так — то? Я же все освобождаю? Или нет?

И тут мне сильно не хватало Valgrind, с его трассировкой вызовов.

В итоге, после 15 минут прогугливания, я нашел аналог Valgrind — Visual Leak Detector. Это сторонняя библиотека, обертка над CRT, которая обещала показывать трассировку! Это то, что мне необходимо.

Чтобы её установить, необходимо перейти в репозиторий и в assets найти vld-2.5.1-setup.exe

Правда, последнее обновление было со времен Visual Studio 2015, но оно работает и с Visual Studio 2019. Установка стандартная, просто следуйте инструкциям.

Чтобы подключить VLD, необходимо прописать #include <vld.h> .

Преимущество этой утилиты заключается в том, что можно не запускать в режиме debug (F5), ибо все выводится в консоль. В самом начале будет выводиться это:

И вот, что будет выдавать при утечке памяти:

Вот, я вижу трассировку! Так, а где строки кода? А где названия функций?

Ладно, обещание сдержали, однако это не тот результат, который я хотел.

Остается один вариант, который я нашел в гугле: моментальный снимок памяти. Он делается просто: в режиме debug, когда доходите до return 0, необходимо в средстве диагностики перейти во вкладку «Использование памяти» и нажать на «Сделать снимок». Возможно, у вас будет отключена эта функция, как на первом скриншоте. Тогда необходимо включить, и перезапустить дебаг.

После того, как вы сделали снимок, у вас появится под кучей размер. Я думаю, это сколько всего было выделено памяти в ходе работы программы. Нажимаем на этот размер. У нас появится окошко, в котором будут содержаться объекты, которые хранятся в этой куче. Чтобы посмотреть подробную информацию, необходимо выбрать объект и нажать на кнопку «Экземпляры представления объекта Foo».

Да! Это победа! Полная трассировка с местоположением вызовов! Это то, что было необходимо изначально.

Linux — разработка
Теперь, посмотрим, что творится в Linux.

В Linux существует утилита valgrind. Чтобы установить valgrind, необходимо в консоли прописать sudo apt install valgrind (Для Debian-семейства).

Я написал небольшую программу, которая заполняет динамический массив, но при этом, не очищается память:

Скомпилировав программу с помощью CLang, мы получаем .out файл, который мы подкидываем valgrind’у.

С помощью команды valgrind ./a.out . Как работает valgrind, думаю, есть смысл описать в отдельной статье, а сейчас, как выполнится программа, valgrind выведет это:

Таким образом, valgrind пока показывает, сколько памяти было потеряно. Чтобы увидеть, где была выделена память, необходимо прописать —leak-check=full , и тогда, valgrind, помимо выше описанного, выведет это:

Конечно, тут не указана строка, однако уже указана функция, что не может не радовать.

Есть альтернативы valgrind’у, такие как strace или Dr.Memory, но я ими не пользовался, да и они применяется в основном там, где valgrind бессилен.

Выводы

Я рад, что мне довелось столкнуться с проблемой поиска утечки памяти в Visual Studio, так как я узнал много новых инструментов, когда и как ими пользоваться и начал разбирать, как работают эти инструменты.

Похожие статьи