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

后端 未结 24 3069
暗喜
暗喜 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:58

    Yes that may, since your allocating with new[] but deallocating with delelte, yes malloc/free is safer here, but in c++ you should not use them since they won't handle (de)constructors.

    Also your code will call the deconstructor, but not the constructor. For some structs this may cause a memory leak (if the constructor allocated further memory, eg for a string)

    Better would be to do it correctly, as this will also correctly call any constructors and deconstructors

    STRUCT* pStruct = new STRUCT;
    ...
    delete pStruct;
    

提交回复
热议问题