아래 코드를 이해하는 데 도움이 필요합니다 ... alloc은 메모리를 할당하기 위해 오버로드 된 new 연산자에 의해 호출되는 함수입니다. ..새 메모리 오버로드 및 삭제 C++ 메모리 할당 추적
// get original block
void* mem = static_cast<char*>(pMemory) - sizeof(std::size_t); //?
*static_cast<std::size_t*>(mem) = pAmount; //please explain?
return static_cast<char*>(mem) + sizeof(std::size_t); //?
및 코드는 다음과 같습니다 : 나는 문제가 특히 다음 캐스트를 이해하려고 노력 데
const std::size_t allocation_limit = 1073741824; // 1G
std::size_t totalAllocation = 0;
void* allocate(std::size_t pAmount)
{
// make sure we're within bounds
assert(totalAllocation + pAmount < allocation_limit);
// over allocate to store size
void* mem = std::malloc(pAmount + sizeof(std::size_t));
if (!mem)
return 0;
// track amount, return remainder
totalAllocation += pAmount;
*static_cast<std::size_t*>(mem) = pAmount;
return static_cast<char*>(mem) + sizeof(std::size_t);
}
void deallocate(void* pMemory)
{
// get original block
void* mem = static_cast<char*>(pMemory) - sizeof(std::size_t);
// track amount
std::size_t amount = *static_cast<std::size_t*>(mem);
totalAllocation -= pAmount;
// free
std::free(mem);
}
그래서 * static_cast <표준 :이 size_t *> (MEM) =이 될 수 pAmount size_t * ptr = static_cast (mem) ... 여기서 ptr은 할당 된 메모리의 시작을 가리키며 * ptr = pAmount; ? –
maxpayne
@maxpayne : 맞습니다. –
allocate 함수에서 리턴 값 0과 리턴 NULL 사이에 차이가 있습니까? 값이 0 인 매크로는 null입니까? – maxpayne