https://stackoverflow.com/questions/197675/how-does-delete-know-the-size-of-the-operand-array


  • 22
    Sorry, but this answer misses the point. What QuantumPete described is basically "How free knows how much memory to deallocate". Yes, the memory block size is stored "somewhere" by malloc (normally in the block itself), so that's how free knows. However, new[]/delete[] is a different story. The latter basically work on top of malloc/freenew[] also stores the number of elements it created in the memory block (independently of malloc), so that later delete[] can retrieve and use that number to call the proper number of destructors. – AnT Oct 24 '09 at 4:35
  • 18
    I.e. physically two counters are stored in the block: block size (by malloc) and element count (by new[]). Note, that the former cannot be used to calculate the latter, since in general case the size of the memory block can be larger than really necessary for the array of requested size. Also note that the array element counter is only needed for types with non-trivial destructor. For types with trivial destructor the counter is not stored by new[] and, of course, not retrieved by delete[]. – AnT Oct 24 '09 at 4:38


malloc은 자기가 할당한 크기를 어딘가에 저장해둔다.(보통은 할당한 블록에) free는 이를 사용한다.

new[]는 malloc의 정보에 추가로 (일반적인 소멸자가 아닌 타입일 때) 자신이 삭제해야할 갯수를 저장해둔다. delete[]는 이를 사용한다.


할당되는 메모리 블록의 크기는 우리가 생각하는 크기 외에 추가로 할당될 수 있기에 이를 통해 배열의 크기를 추적하는 건 불가능하다.