bds 2006 C hidden memory manager conflicts (class new / delete[] vs. AnsiString)

After extensive debugging i finely isolated the problem.
Memory management of bds2006 Turbo C++ became corrupt after you try to call any delete for already deleted pointer. for example:

BYTE *dat=new BYTE[10],*tmp=dat;
delete[] dat;
delete[] tmp;

After this is memory management not reliable. (‘new’ can allocate already allocated space)

Of course deletion of the same pointer twice is bug on programmers side, but i have found the real cause of all my problems which generates this problem (without any obvious bug in source code) see this code:

//---------------------------------------------------------------------------
class test
    {
public:
    int siz;
    BYTE *dat;
    test()
        {
        siz=10;
        dat=new BYTE[siz];
        }
    ~test()
        {
        delete[] dat;   // <- add breakpoint here
        siz=0;
        dat=NULL;
        }
    test& operator = (const test& x)
        {
        int i;
        for (i=0;i<siz;i++) if (i<x.siz) dat[i]=x.dat[i];
        for (   ;i<siz;i++) dat[i]=0;
        return *this;
        }
    };
//---------------------------------------------------------------------------
test get()
    {
    test a;
    return a;   // here call a.~test();
    }           // here second call a.~test(); 
//---------------------------------------------------------------------------
void main()
    {
    get();
    }
//---------------------------------------------------------------------------

In function get() is called destructor for class a twice. Once for real a and once for its copy because I forget to create constructor

test::test(test &x);

[Edit1] further upgrades of code

OK I have refined the initialization code for both class and struct even templates to fix even more bug-cases. Add this code to any struct/class/template and if needed than add functionality

T()     {}
T(const T& a)   { *this=a; }
~T()    {}
T* operator = (const T *a) { *this=*a; return this; }
//T* operator = (const T &a) { ...copy... return this; }
  • T is the struct/class name
  • the last operator is needed only if T uses dynamic allocations inside it if no allocations are used you can leave it as is

This also resolves other compiler issues like this:

If anyone have similar problems hope this helps.

Also look at traceback a pointer in c++ code mmap if you need to debug your memory allocations…

Leave a Comment