LabWindows/CVI

Dynamic Memory

LabWindows/CVI provides run-time error checking for pointers and arrays in dynamically allocated memory.

You can use the ANSI C Library functions malloc or calloc to allocate dynamic memory. These functions return void * values that you must cast to some other type before you can use the memory. During program execution, LabWindows/CVI uses the first such cast on the return value of each call to these functions to determine the type of the object that will be stored in the dynamic memory. Subsequent casts to different types can disable checking on the dynamic data, as explained in the Pointer Casting discussion in this section.

You can use the realloc function to resize dynamically allocated memory. This function increases or decreases the size of the object associated with the dynamic memory. LabWindows/CVI adjusts the user protection information accordingly.

Avoid Unassigned Dynamic Allocation in Function Parameters

The LabWindows/CVI run-time error checking mechanism dynamically allocates data to keep track of pointers that you dynamically allocate in your program. When you no longer use the pointers, LabWindows/CVI uses garbage collection to deallocate the pointers' corresponding dynamic memory.

A case exists where the garbage collection fails to retrieve all the memory that the run-time error checking mechanism allocated. This case occurs when the all of the following points are true:

  • You pass the return value of one function to another function.
  • The return value is a pointer to dynamically allocated memory.
  • You do not assign the pointer to a variable in the argument expression.

The following code is an example of such a case.

MyFunc (1, 2, malloc(7));

This call passes the return value from malloc to MyFunc but does not assign the return value to a variable. If you make this call repeatedly in your program with run-time checking enabled, you lose a small amount of memory each time.

Change the code as follows to avoid this problem.

void *p;
MyFunc (1, 2, p = malloc(7));

The following code also works and uses better programming style.

void *p;
p = malloc(7);
MyFunc (1, 2, p);