Finding Memory Errors

You can select a topic from this diagram:

Glossary What's New Utilities Used by the IDE Getting System Information Using Code Coverage Common Wizards Reference Preparing Your Target Developing Photon Applications Developing C/C++ Programs Where Files Are Stored Building OS and Flash Images Migrating to the 6.3 Release Tutorials IDE Concepts About This Guide Analyzing Your System With Kernel Tracing Profiling an Application Finding Memory Errors Debugging Programs Managing Source Code Launch Configurations Reference

Workflow diagram with memory chapter highlighted


Use the QNX Memory Analysis perspective to solve memory problems.

In this chapter...

Introduction

Have you ever had a customer say, "The program was working fine for days, then it just crashed"? If so, chances are good that your program had a memory error -- somewhere.

Debugging memory errors can be frustrating; by the time a problem appears, often by crashing your program, the corruption may already be widespread, making the source of the problem difficult to trace.

The QNX Memory Analysis perspective shows you how your program uses memory and can help ensure that your program won't cause problems. The perspective helps you quickly pinpoint memory errors in your development and testing environments before your customers get your product.


Note: The QNX Memory Analysis perspective may produce incorrect results when more than one IDE is communicating with the same target system. To use this perspective, make sure only one IDE is connected to the target system.

Memory management in QNX Neutrino

By design, Neutrino's architecture helps ensure that faults, including memory errors, are confined to the program that caused them. Programs are less likely to cause a cascade of faults because processes are isolated from each other and from the microkernel. Even device drivers behave like regular debuggable processes:

Introduction; Neutrino architecture

This robust architecture ensures that crashing one program has little or no effect on other programs throughout the system. When a program faults, you can be sure that the error is restricted to that process's operation.

Neutrino's full memory protection means that almost all the memory addresses your program encounters are virtual addresses. The process manager maps your program's virtual memory addresses to the actual physical memory; memory that is contiguous in your program may be transparently split up in your system's physical memory:

Introduction; Contiguous memory

The process manager allocates memory in small pages (typically 4 KB each). To determine the size for your system, use the sysconf(_SC_PAGESIZE) function.

As you'll see when you use the Memory Information view of the QNX System Information perspective, the IDE categorizes your program's virtual address space as follows:


Introduction: Process memory


Process memory layout on an x86.

The Memory Information and Malloc Information views of the QNX System Information perspective provide detailed, live views of a process's memory. See the Getting System Information chapter for more information.

Program memory

Program memory holds the executable contents of your program. The code section contains the read-only execution instructions (i.e. your actual compiled code); the data section contains all the values of the global and static variables used during your program's lifetime:

Introduction: Memory, program

Stack memory

Stack memory holds the local variables and parameters your program's functions use. Each process in Neutrino contains at least the main thread; each of the process's threads has an associated stack. When the program creates a new thread, the program can either allocate the stack and pass it into the thread-creation call, or let the system allocate a default stack size and address:

Introduction: Memory, stack 2

When your program runs, the process manager reserves the full stack in virtual memory, but not in physical memory. Instead, the process manager requests additional blocks of physical memory only when your program actually needs more stack memory. As one function calls another, the state of the calling function is pushed onto the stack. When the function returns, the local variables and parameters are popped off the stack.

The used portion of the stack holds your thread's state information and takes up physical memory. The unused portion of the stack is initially allocated in virtual address space, but not physical memory:

Introduction: Memory, stack 1

At the end of each virtual stack is a guard page that the microkernel uses to detect stack overflows. If your program writes to an address within the guard page, the microkernel detects the error and sends the process a SIGSEGV signal.

As with other types of memory, the stack memory appears to be contiguous in virtual process memory, but not necessarily so in physical memory.

Shared-library memory

Shared-library memory stores the libraries you require for your process. Like program memory, library memory consists of both code and data sections. In the case of shared libraries, all the processes map to the same physical location for the code section and to unique locations for the data section:

Introduction: Memory, library

Object memory

Object memory represents the areas that map into a program's virtual memory space, but this memory may be associated with a physical device. For example, the graphics driver may map the video card's memory to an area of the program's address space:

Introduction: Memory, object

Heap memory

Heap memory represents the dynamic memory used by programs at runtime. Typically, processes allocate this memory using the malloc(), realloc(), and free() functions. These calls ultimately rely on the mmap() function to reserve memory that the malloc library distributes.

The process manager usually allocates memory in 4 KB blocks, but allocations are typically much smaller. Since it would be wasteful to use 4 KB of physical memory when your program wants only 17 bytes, the malloc library manages the heap. The library dispenses the paged memory in smaller chunks and keeps track of the allocated and unused portions of the page:

Introduction: Memory, heap1

Each allocation uses a small amount of fixed overhead to store internal data structures. Since there's a fixed overhead with respect to block size, the ratio of allocator overhead to data payload is larger for smaller allocation requests.

When your program uses the malloc() function to request a block of memory, the malloc library returns the address of an appropriately sized block. To maintain constant-time allocations, the malloc library may break some memory into fixed blocks. For example, the library may return a 20-byte block to fulfill a request for 17 bytes, a 1088-byte block for a 1088-byte request, and so on.

When the malloc library receives an allocation request that it can't meet with its existing heap, the library requests additional physical memory from the process manager. As your program frees memory, the library merges adjacent free blocks to form larger free blocks wherever possible. If an entire memory page becomes free as a result, the library returns that page to the system. The heap thus grows and shrinks in 4 KB increments:

Introduction: Memory, heap2

What the Memory Analysis perspective can reveal

The main system allocator has been instrumented to keep track of statistics associated with allocating and freeing memory. This lets the memory statistics module unintrusively inspect any process's memory usage.

When you launch your program with the Memory Analysis tool, your program uses the debug version of the malloc library (libmalloc_g.so). Besides the normal statistics, this library also tracks the history of every allocation and deallocation, and provides cover functions for the string and memory functions (e.g. strcmp(), memcpy(), memmove()). Each cover function validates the corresponding function's arguments before using them. For example, if you allocate 16 bytes, then forget the terminating NUL character and attempt to copy a 16-byte string into the block using the strcpy() function, the library detects the error.

The debug version of the malloc library uses more memory than the nondebug version. When tracing all calls to malloc() and free(), the library requires additional CPU overhead to process and store the memory-trace events.


Note: Be sure to occasionally check the Download Center on our website for updated versions of the debug malloc library.

The QNX Memory Analysis perspective can help you pinpoint and solve various kinds of problems, including:

Memory leaks

Memory leaks can occur if your program allocates memory and then forgets to free it later. Over time, your program consumes more memory than it actually needs.

In its mildest form, a memory leak means that your program uses more memory than it should. QNX Neutrino keeps track of the exact memory your program uses, so once your program terminates, the system recovers all the memory, including the lost memory.

If your program has a severe leak, or leaks slowly but never terminates, it could consume all memory, perhaps even causing certain system services to fail.

The following tabs in the Memory Analysis editor can help you find and fix memory leaks:

For more information about the memory analysis editor, see the description of the Memory Analysis editor view later in this chapter. For detailed descriptions about memory errors, see Interpreting errors during memory analysis.

Memory errors

Memory errors can occur if your program tries to free the same memory twice or uses a stale or invalid pointer. These "silent" errors can cause surprising, random application crashes. The source of the error can be extremely difficult to find, because the incorrect operation could have happened in a different section of code long before an innocent operation triggered a crash. For more information about how to interpret memory errors during memory analysis, see the topic Interpreting errors during memory analysis later in this chapter.

In the event of a memory error, the IDE can:

The resulting action that the IDE takes depends on the setting that you chose in the Memory Analysis Tooling part of the launch configuration (see "Analyzing your program," later in this chapter).

The Memory Analysis editor's Errors and Statistics tabs display memory errors and -- if possible -- the exact line of source code that generated each error. The Trace tab lets you find the prior call that accessed the same memory address, even if your program made the call days earlier. For more information about the memory analysis editor, see the description of the Memory Analysis editor later in this chapter. For detailed descriptions about memory errors, see Interpreting errors during memory analysis.


Note: To learn more about the common causes of memory problems, see the topic Heap Analysis: Making Memory Errors a Thing of the Past chapter of the QNX Neutrino Programmer's Guide.

Analyzing your program

To extract the most information from your program, you should launch it with the Memory Analysis tool enabled:

  1. Create a Run or Debug type of QNX Application launch configuration as you normally would, but don't click Run or Debug.
  2. In the Create, manage, and run configurations dialog, click the Tools tab.
  3. Click Add/Delete Tool.
  4. In the Tools Selection dialog, check Memory Analysis Tooling:

    Adding a tool

  5. Click OK.
  6. Click the Memory Analysis Tooling tab.
  7. To configure the Memory Analysis settings for your program, click the disclosure triangle for the appropriate set of options:

    Memory Analysis tool

    Memory Errors
    This group of configuration options controls the Memory Analysis tool's behavior when memory errors are detected.
    Enable error detection
    Check this to detect memory allocation, deallocation, and access errors:
    Verify parameters in string and memory functions
    When enabled, check the parameters in calls to str*() and mem*() functions for sanity.
    Perform full heap integrity check on every allocation/deallocation
    When enabled, check the heap's memory chains for consistency before every allocation or deallocation. Note that this checking comes with a performance penalty.
    Enable bounds checking (where possible)
    When enabled, check for buffer overruns and underruns. Note that this is possible only for dynamically allocated buffers.
    When an error is detected
    Memory Analysis takes the selected action when a memory error is detected. By default, it reports the error and attempts to continue, but you can also choose to launch the debugger or terminate the process.
    Limit trace-back depth to
    Specify the number of stack frames to record when logging a memory error.
    Perform leak check every (ms)
    Specify how often you want to check for leaks. Note that this checking comes with a performance penalty.
    Perform leak check when process exits
    When checked, look for memory leaks when the process exits, before the operating system cleans up the process's resources.
    Memory Tracing
    This group of configuration options controls the Memory Analysis tool's memory tracing features.
    Enable memory allocation/deallocation tracing
    When checked, trace all memory allocations and deallocations.
    Limit back-trace depth to
    Specify the number of stack frames to record when tracing memory events.
    Minimum allocation to trace
    The size, in bytes, of the smallest allocation that will be traced. Use 0 to trace all allocations.
    Maximum allocation to trace
    The size, in bytes, of the largest allocation that will be traced. Use 0 to trace all allocations.
    Perform tracing every (ms)
    How often to collect information about your program's allocation and deallocation activity. When setting this, consider how often your program allocates and deallocates memory, and how long you plan to run the program.
    Memory Snapshots
    Controls the Memory Analysis tool's memory snapshot feature.
    Memory Snapshots
    Check this to enable memory snapshots.
    Perform snapshot every (ms)
    Specify the number of milliseconds between each memory snapshot.
    Bins counters (comma separated) ex: 2,4,6,8,...
    A comma-separated list of the memory bins you want to trace.
    Library search paths
    A list of the libraries that you want to have backtrace information for. For more information, see "Analyzing shared objects," later in this chapter.
    Target Settings
    These settings let you specify details about how memory debugging will be handled on the target system.
    Malloc library:
    The full path on the target to the memory-debugging library, usually libmalloc_g.so.
    Send traces to:
    The full path to the device that will receive trace messages. The default is /dev/dbgmem. You can also log traces to a file on the target; for more information, see "Using a file to log the trace," later in this chapter.
    Send events to:
    The full path to the device that will receive memory events. The default is /dev/dbgmem.
    Create control thread
    Check this to use a separate thread for memory tracing operations.
    Use dladdr to find dll names
    Check this if you'd like to get backtrace information from shared objects that were built with debugging information. For more information, see "Analyzing shared objects," later in this chapter.
    Show debug output on console
    Check this to show messages from the memory-debugging library in the Console view.
    Data Collection
    This setting lets you choose the type of database used to register the memory traces and events:
    Neutrino Derby Data Collection
    A file database that's slower, but uses less memory.
    NTO HSQLDB Data Collection
    An in-memory database. It's fast, but before grabbing large traces, you should make sure the Java VM has enough memory. You can use the -Xmx option in qde.ini to specify the amount of memory for the Java VM. You must restart the IDE for this option to take effect.

    For example, to collect 2 million events and memory traces, you'll need about 2 GB of memory; specify -Xmx2048m. The default size is 512 MB.

  8. If you want the IDE to automatically change to the QNX Memory Analysis perspective when you run or debug, check Switch to this tool's perspective on launch.
  9. Click Apply to save your changes.
  10. Click Run, Debug, or Profile. The IDE starts your program and lets you analyze your program's memory.

Note: Don't run more than one Memory Analysis session on a given target at a time, because the results may not be accurate.

Interpreting errors during memory analysis

Although the QNX Memory Analysis perspective shows you how your program uses memory, and can quickly direct you to memory errors in your development and testing environments, you need to understand the types of memory errors that you might run into.

During memory analysis, you may encounter the following types of memory errors:

When memory errors occur, the IDE can:

Regardless of which course of action the IDE takes, all of the error and non-error events are available to you in the Trace Event Log.

To include the Trace Event Log in your Task view:

To enable memory analysis:

  1. From an existing launch configuraion, select the Tools tab.
  2. Select Add/Delete Tool.
  3. Select Memory Analysis Tooling and click OK.

    Memory Analysis Tooling

  4. Select any required memory tools and specify any desired options for that tool.

After you configure the IDE for memory analysis, you can begin to use the results to identify the types of memory errors in your programs, and then trace them back to your code.

To view the memory errors identified by the IDE, and then navigate to those errors:

  1. After enabling Memory Analysis in a launch configuration, run that configuration.
  2. In the Session view, double-click your desired launch configuration.

    A dialog with the same name will contain a list of memory errors that the IDE encountered in your program.

    Memory Analysis Tooling

    In addition, a multi-tab editor will open at the bottom of the Workbench window.

    Memory Analysis Tooling

  3. Click the Errors tab.
  4. In the window that lists the types of errors, select an error. Notice that the information in the Errors tab dynamically updates to reflect the error that you've selected.
  5. On the Errors tab, double-click on an error to navigate to that error in the code editor.
  6. Modify the code, as required, to correct the memory error for the selected error.

Illegal deallocation of memory

The Illegal deallocation of memory occurs when a free() operation is performed on a pointer that does not point to an appropriate heap memory segment. This type of error can occur when you attempt to do any of the following activities:

Consequences

The illegal deallocation of memory would generate the following runtime errors:

Detecting the error


Note: For instructions about enabling error detection in the IDE, see Enabling error detection.

In the QNX IDE, the memory analysis feature would detect this error (if error detection is enabled), and it would trap the illegal deallocation error when any of the following functions are called:

Enabling error detection

To enable error detection for the illegal deallocation of memory:

  1. In the Launch Configuration window, select the Tools tab.
  2. Select the Enable error detection checkbox.
  3. Select the Enable check on realloc()/free() argument checkbox.
  4. Click OK.

Message returned to the QNX IDE

In the IDE, you can expect the message for this type of memory error to include the following types of information and detail:

For a list of error messages returned by the Memory Analysis tool, see Error message summary (memory analysis).

How to address the illegal deallocation of memory

To help address this memory problem, try the following:

Example

The following code shows an example of the illegal deallocation of memory.

int main(int argc, char ** argv){
  char * str = "";
  if (argc>1) {
     str = malloc(10);
     // ...
  }
  printf("Str: %s\n",str);
  free(str);
  return 0;
}

Null pointer dereference

A NULL pointer derefence is a sub-type of an error causing a segmentation fault. It occurs when a program attempts to read or write to memory with a NULL pointer.

Consequences

Running a program that contains a NULL pointer dereference generates an immediate segmentation fault error.


Note: For instructions about enabling error detection in the IDE, see Enabling error detection.

When the memory analysis feature detects this type of error, it traps these errors for any of the following functions (if error detection is enabled) when they are called within your program:


Note: The memory analysis feature does not trap errors for the following functions when they are called:
  • memccpy()
  • memchrv()
  • memmove()
  • memcpy()
  • memcmp()
  • memset()
  • bcopy()
  • bzero()
  • memccpy()
  • memchrv()
  • memmove()
  • memcpy()
  • memcmp()
  • memset()
  • bcopy()
  • bzero()
  • bcmp()
  • bcmp()

Enabling error detection

To enable error detection for the a null pointer dereference:

  1. In the Launch Configuration window, select the Tools tab.
  2. Select the Enable error detection checkbox.
  3. To detect the passing of a zero (0) pointer to string and memory functions, select Verify parameters in string and memory functions.
  4. To detect the freeing of a zero (0) pointer, select Enable check on realloc()/free() argument.

Message returned to the QNX IDE

In the IDE, you can expect the message for this type of memory error to include the following types of information and detail:

For a list of error messages returned by the Memory Analysis tool, see Error message summary (memory analysis).

How to address a null pointer dereference

You can perform an explicit check for NULL() for all pointers returning from functions that can return NULL(), and when parameters are passed to the function.

Example

The following code shows an example of a NULL pointer dereference.

int main(int argc, char ** argv){
  char buf[255];
  char * ptr = NULL;
  if (argc>1) {
    ptr = argv[1];
  }
  strcpy(str,ptr);
  return 0;
}

Buffer overflow

A buffer overflow error occus when a program unintentionaly writes to a memory area that is out of bounds of the buffer it intended to write to.

Consequences

A buffer overflow would generate the following runtime errors:

Detecting the error

The Memory Analysis tool can detect a limitied number of possible buffer overflows with following conditions:

Enabling error detection

To enable error detection for a buffer overflow or underflow:

  1. In the Launch Configuration window, select the Tools tab.
  2. Select Enable error detection checkbox.
  3. To detect an immediate overflow, select Verify parameters in string and memory functions.
  4. To detect a small overflow in block's memory overhead area, select Enabled bounds checking (where possible)
  5. To detect a corrupted heap, caused by overflowing other regions, select Perform full integrity check on every allocation/deallocation.

Message returned to the QNX IDE

In the IDE, you can expect the message for this type of memory error to include the following types of information and detail:

For a list of error messages returned by the Memory Analysis tool, see Error message summary (memory analysis).

How to address buffer overflow errors

Locate the code where the actual overflow occured. Ensure that the size of the memory region is always accompanied by the pointer itself, verify all unsafe operations, and that the memory region is large enough to accommodate the data going into that location.

Example

The following code shows an example of a buffer overflow trapped by a library function.

int main(int argc, char ** argv){
  char * ptr = NULL;
  ptr = malloc(12);
  strcpy(ptr,"Hello World!");
  return 0;
}

The following code shows an example of a buffer overflow trapped by a post-heap check in a free() function.

int main(int argc, char ** argv){
  char * ptr = NULL;
  ptr = malloc(12);
  ptr[12]=0;
  free(pre);
  return 0;
}

Using freed memory

If you attempt to read or write to memory that was previously freed, the result will be a conflict and the program will generate a memory error. For example, if a program calls the free() function for a particular block and then continues to use that block, it will create a re-use problem when a malloc() call is made.

Consequences

Using freed memory would generate the following runtime errors:

Detecting the error

The Memory Analysis tool can delect only a limited number of situations where free memory is read/written with following conditions:

Enabling error detection

To enable error detection when using freed memory:

  1. In the Launch Configuration window, select the Tools tab.
  2. Select Enable error detection checkbox
  3. To detect usage of freed memory, select Verify parameters in string and memory functions.
  4. To detect writing to a freed memory area, select Enabled bounds checking (where possible).

Message returned to the QNX IDE

In the IDE, you can expect the message for this type of memory error to include the following types of information and detail:

For a list of error messages returned by the Memory Analysis tool, see Error message summary (memory analysis).

How to address freed memory usage

Set the pointer of the freed memory to 0 immediately after the free(), unless it is a local variable that goes out of the scope in the next line of the program.

Example

The following code shows an example using already freed memory.

int main(int argc, char ** argv){
  char * ptr = NULL;
  ptr = malloc(13);
  free(ptr);
  strcpy(ptr,"Hello World!");
  return 0;
}

Uninitialized memory read

If you attempt to read or write to memory that was previously freed, the result will be a conflict and the program will generate a memory error because the memory is not initialized.

Consequences

Using an uninitialized memory read would generate a random data read runtime error.

Detecting the error

Typically, the IDE does not detect this type of error; however, the Memory Analysis tool does trap the condition of reading uninitialized data from a recently allocated memory region.

For a list of error messages returned by the Memory Analysis tool, see Error message summary (memory analysis).

How to address random data read issues

Use the calloc() function, which always initializes data with zeros (0).

Example

The following code shows and example of an uninitialized memory read.

int main(int argc, char ** argv){
  char * ptr = NULL;
  ptr = malloc(13);
  if (argc>1)
  strcpy(ptr,"Hello World!");
  ptr[12]=0;
  printf("%s\n",ptr);
  return 0;
}

Resource (memory) leaks

Memory leaks can occur if your program allocates memory and then does not free it. For example, a resource leak can occur in a memory region that no longer has references from a process.

Consequences

Resource leaks would generate the following runtime errors:

Detecting the error

This error would be trapped during the following circumstances:

Message returned to the QNX IDE

In the IDE, you can expect the message for this type of memory error to include the following types of information and detail:

  1. In the Launch Configuration window, select the Tools tab.
  2. Select "Perform leak check when process exits" checkbox.
  3. Optional: Enter "Perform leak check every (ms)" number of ms 0 >. The minimum depends on target speed; however, on avarage, it should be no less than 100ms.

Message returned to the QNX IDE

In the IDE, you can expect the message for this type of memory error to include the following types of information and detail:

For a list of error messages returned by the Memory Analysis tool, see Error message summary (memory analysis).

How to address resource (memory) leaks

To address resource leaks in your program, ensure that memory is deallocated on all paths, inluding error paths.

Example

The following code shows an example of a memory leak.

int main(int argc, char ** argv){
  char * str = malloc(10);
  if (argc>1) {
     str = malloc(20);
     // ...
  }
  printf("Str: %s\n",str);
  free(str);
  return 0;
}

Functions checked for memory errors during memory analysis

During memory analysis, the following functions are checked for memory errors:

Error message summary (memory analysis)

The following table shows a summary of potential error messages you might encounter during memory analysis:

Message Caused by Description
"no errors"
"allocator inconsistency - Malloc chain is corrupted, pointers out of order" A buffer overflow occurred in the heap. The heap memory is corrupted.
"allocator inconsistency - Malloc chain is corrupted, end before end pointer" A buffer overflow occurred in the heap. The heap memory is corrupted.
"pointer does not point to heap area" The illegal deallocation of memory. You attempted to free non-heap memory.
"possible overwrite - Malloc block header corrupted" A buffer overflow occurred in the heap. The heap memory is corrupted.
"allocator inconsistency - Pointers between this segment and adjoining segments are invalid" A buffer overflow occurred in the heap. The heap memory is corrupted.
"data has been written outside allocated memory block" A buffer overflow occurred in the heap. The Program attempted to write data to a region beyond allocated memory.
"data in free'd memory block has been modified" Attempting to use memory that was previously freed. The Program is attempting to write to a memory region that was previously freed.
"data area is not in use (can't be freed or realloced)" A buffer overflow occurred in the heap. The heap memory is corrupted.
"unable to get additional memory from the system" All memory resources are exhausted. There are no more memory resources to allocate.
"pointer points to the heap but not to a user writable area" A buffer overflow occurred in the heap. The heap memory is corrupted.
"allocator inconsistency - Malloc segment in free list is in-use" A buffer overflow occurred in the heap. The heap memory is corrupted.
"malloc region doesn't have a valid CRC in header" A buffer overflow occurred in the heap. The heap memory is corrupted.
"free'd pointer isn't at start of allocated memory block" An illegal deallocation of memory. An attempt was made to deallocate the pointer that shifted from its original value when it was returned by the allocator.

Memory analysis GUI flags and corresponding environment variables

The following table shows a summary of graphical user interface options (flags) and their corresponding environment variables:

Environment variable Where to find in MAT GUI What option to set
MALLOC_TRACEBT=5 Memory Tracing-->Enable memory allocation/deallocation tracing Limit backtrace depth to: 5
MALLOC_CKALLOC=1 Memory Errors-->Enable error detection Enable check on realloc()/free() argument
MALLOC_CKACCESS=1 Memory Errors-->Enable error detection Verify the parameters in the string and memory functions
MALLOC_CKCHAIN=1 Memory Errors-->Enable error detection Perform a full heap integrity check on every allocation/deallocation
MALLOC_WARN=0 Memory Errors-->Enable error detection When an error is detected: report the error and continue
MALLOC_DUMP_ LEAKS=1 Memory Errors-->Enable error detection Perform leak check when process exits
MALLOC_TRACEMIN= 20 Memory Tracing Minimum allocation to trace: 20
MALLOC_BTDEPTH=10 Memory Error Limit back-trace depth to: 10
MALLOC_TRACE= /dev/dbgmem Memory Tracing Enable memory allocation/deallocation tracing
MALLOC_ERRFILE= /dev/null N/A N/A
MALLOC_FATAL=0 Memory Errors-->Enable error detection When an error is detected: report the error and continue
MALLOC_FILLAREA=1 Memory Errors-->Enable error detection Enable bounds checking (where possible)
MALLOC_TRACEMAX= 30 Memory Tracing Maximum allocation to trace: 20
MALLOC_CTHREAD=1 Memory Errors-->Target Settings Create control thread
MALLOC_EVENTFILE= /dev/dbgmem Memory Errors-->Target Settings Send envents to:
MALLOC_STAT_BINS= 2,4,8,16,32 Memory Snapshots-->Bin counters N/A
LD_PRELOAD= /tmp/libmalloc_g.so Target Settings Malloc library: /tmp/libmalloc_g.so

Using a file to log the trace

You can perform memory analysis on a running program, or you can use log the trace to a file on the target system. The advantage of logging the trace is that doing so frees up qconn resources; you run the process and do the analysis later.


Note: When analyzing the data from a log file, you can't do any backtracing.

To log the trace to a file:

  1. Open the Launch configuration and go to the Memory Analysis Tooling tab.
  2. Expand the Target Settings.
  3. By default, the Send traces to: field is set to /dev/dbgmem, which the qconn agent reads. Specify the name of the file on the target system (e.g. /tmp/log.memory) where you'd like to send the traces instead.
  4. Run your application on the target.
  5. Copy the file back to the host, and then choose Import libmalloc_g events from the Session view's right-click menu.

    A dialog appears:

    Importing libmalloc_g trace events

  6. Choose an existing session or create a new one.
  7. Browse to the file that you copied from the target, and then click OK. The IDE reparses the file for viewing.

You can also do this on the command line by setting the appropriate environment variables. For example:

LD_PRELOAD=/tmp/libmalloc_g.so MALLOC_TRACE=/tmp/log.memory
    

Analyzing a running program

You can perform memory analysis on a running program, if that program was started using the debug malloc library and the proper environment variables. Once the program is running, you can attach the Memory Analysis perspective and gather your data.

Launching with debug malloc

To start a program using the debug malloc library: Launch the program using the LD_PRELOAD (set to the debug malloc library) and MALLOC_CTHREAD (set to 1) environment variables:
LD_PRELOAD=/tmp/libmalloc_g.so MALLOC_CTHREAD=1 ./my_app

Attaching to a running process

As mentioned above, you can analyze memory events and traces for a running process. To do this, you need to create a launch profile, as follows:

  1. If the Run menu doesn't include a Profile entry, add it like this:
    1. Choose Customize Perspective ... from the Window menu.
    2. Choose the Commands tab.
    3. In the list of checkboxes, enable the Profile checkbox.
    4. Click OK.
  2. Choose Run-->Profile....
  3. Set up the launch configuration.

After launching, a dialog appears with a list of the running processes on the box. Choose the process you want to attach to; the Session view then lists it. When you select the process in the Session view, the editor displays the information about it.

When you're done, disconnect from the process and let it continue.

Analyzing shared objects

In order to analyze shared objects, you must set up the Memory Analysis Tooling tab of your launch configuration:

In the Session View, you can expand your session, expand your process, and then select a shared object to view its memory events and traces in a new tab in the editor.

Associated views

The QNX Memory Analysis perspective includes the following views:

These views are described in the pages that follow.