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

后端 未结 24 3068
暗喜
暗喜 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 13:06

    Yes it will cause a memory leak.

    See this except from C++ Gotchas: http://www.informit.com/articles/article.aspx?p=30642 for why.

    Raymond Chen has an explanation of how vector new and delete differ from the scalar versions under the covers for the Microsoft compiler... Here: http://blogs.msdn.com/oldnewthing/archive/2004/02/03/66660.aspx

    IMHO you should fix the delete to:

    delete [] pStruct;
    

    rather than switching to malloc/free, if only because it's a simpler change to make without making mistakes ;)

    And, of course, the simpler to make change that I show above is wrong due to the casting in the original allocation, it should be

    delete [] reinterpret_cast(pStruct);
    

    so, I guess it's probably as easy to switch to malloc/free after all ;)

提交回复
热议问题