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

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

    I am currently unable to vote, but slicedlime's answer is preferable to Rob Walker's answer, since the problem has nothing to do with allocators or whether or not the STRUCT has a destructor.

    Also note that the example code does not necessarily result in a memory leak - it's undefined behavior. Pretty much anything could happen (from nothing bad to a crash far, far away).

    The example code results in undefined behavior, plain and simple. slicedlime's answer is direct and to the point (with the caveat that the word 'vector' should be changed to 'array' since vectors are an STL thing).

    This kind of stuff is covered pretty well in the C++ FAQ (Sections 16.12, 16.13, and 16.14):

    http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.12

提交回复
热议问题