Will this C++ code cause a memory leak (casting array new)

后端 未结 24 3639
暗喜
暗喜 2021-02-14 12:26

I have been working on some legacy C++ code that uses variable length structures (TAPI), where the structure size will depend on variable length strings. The structures are allo

24条回答
  •  耶瑟儿~
    2021-02-14 12:41

    As highlighted in other posts:

    1) Calls to new/delete allocate memory and may call constructors/destructors (C++ '03 5.3.4/5.3.5)

    2) Mixing array/non-array versions of new and delete is undefined behaviour. (C++ '03 5.3.5/4)

    Looking at the source it appears that someone did a search and replace for malloc and free and the above is the result. C++ does have a direct replacement for these functions, and that is to call the allocation functions for new and delete directly:

    STRUCT* pStruct = (STRUCT*)::operator new (sizeof(STRUCT) + nPaddingSize);
    // ...
    pStruct->~STRUCT ();  // Call STRUCT destructor
    ::operator delete (pStruct);
    

    If the constructor for STRUCT should be called, then you could consider allocating the memory and then use placement new:

    BYTE * pByteData = new BYTE[sizeof(STRUCT) + nPaddingSize];
    STRUCT * pStruct = new (pByteData) STRUCT ();
    // ...
    pStruct->~STRUCT ();
    delete[] pByteData;
    

提交回复
热议问题