PRB: Memory Leak Using Delete Operator

ID: Q118679


The information in this article applies to:


SYMPTOMS

When you release dynamically allocated memory back to the system by using the C++ delete operator in a QuickWin application, a memory leak occurs.


CAUSE

The run-time library provides four versions of the delete operator to deallocate pointers that are near, far, huge, or based. The version that is selected depends on the addressing mode of pointer. For example, if the pointer is a near pointer, the near delete operator is called. If the addressing mode of pointer does not reflect the version of the new operator used to allocate the memory, the incorrect version of the delete operator is called. For example:


   Node __far *fpN;
   fpN = new Node __near;  // convert near to far
   delete fpn;             // far delete invoked for near object 
Here, the compiler chooses the inappropriate delete operator for the pointer, which results in a run-time error.


RESOLUTION

To prevent this problem, explicitly cast the pointer to the addressing mode you want:


   delete (Node __near *)fpN; 


MORE INFORMATION

The following sample code can be used to demonstrate the memory leak. Replace the last two uncommented lines with the commented lines to see the correct output.

Sample Code


   /* Compile options needed: /Mq
   */ 
   #include <malloc.h>
   #include <stdio.h>
   void main()
   {
      char * nearptr;
      char far * farptr;
      printf("\n");
      printf("Starting memory: %u\n",_memavl());
      nearptr = new char;
      farptr = new char __near; // new returns a near pointer
      printf("After memory allocated: memavl=%u\n",_memavl());
      delete nearptr; // the near delete gets called
      delete farptr;  // the far delete gets called for near memory
      printf("After memory is freed : memavl=%u\n",_memavl());
      //delete ( char __near *) farptr; // this will call the correct
   delete
      //printf("After memory is freed : memavl=%u\n",_memavl());
   } 

Additional query words: 7.00 1.00 1.50


Keywords          : kb16bitonly 
Version           : 
Platform          : 
Issue type        : 

Last Reviewed: July 30, 1999