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

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

    I think the is no memory leak.

    STRUCT* pStruct = (STRUCT*)new BYTE [sizeof(STRUCT) + nPaddingSize];
    

    This gets translated into a memory allocation call within the operating system upon which a pointer to that memory is returned. At the time memory is allocated, the size of sizeof(STRUCT) and the size of nPaddingSize would be known in order to fulfill any memory allocation requests against the underlying operating system.

    So the memory that is allocated is "recorded" in the operating system's global memory allocation tables. Memory tables are indexed by their pointers. So in the corresponding call to delete, all memory that was originally allocated is free. (memory fragmentation a popular subject in this realm as well).

    You see, the C/C++ compiler is not managing memory, the underlying operating system is.

    I agree there are cleaner methods but the OP did say this was legacy code.

    In short, I don't see a memory leak as the accepted answer believes there to be one.

提交回复
热议问题