PRB: Memory Leak Using Delete Operator |
Q118679
When you release dynamically allocated memory back to the system by using the C++ delete operator in a QuickWin application, a memory leak occurs.
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:
Here, the compiler chooses the inappropriate delete operator for the pointer, which results in a run-time error.Node __far *fpN; fpN = new Node __near; // convert near to far delete fpn; // far delete invoked for near object
To prevent this problem, explicitly cast the pointer to the addressing mode
you want:
delete (Node __near *)fpN;
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.
/* 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 kbprb
Issue type : kbprb
Technology : kbVCsearch kbAudDeveloper kbPTProdChange kbvc150 kbvc100 kbZNotKeyword3 kbCVC700DOS
|
Last Reviewed: May 9, 2001 © 2001 Microsoft Corporation. All rights reserved. Terms of Use. |