Menu Home

定制operator new记录分配的内存大小

调用operator new的时候在所分配的内存的第一个字节中记录本次new分配的内存大小。

void* operator new(size_t size) throw(bad_alloc){
    
    if(size == 0)
        size = 1;

    void* address = NULL;
    size_t *p = NULL;
    
    while(true) {
        p = (size_t*)malloc(size + sizeof(size_t));
        if(p)
            break;
        new_handler oldHandler = set_new_handler(0);
        set_new_handler(oldHandler);
        
        if(oldHandler)
            (*oldHandler)();
        else
            throw bad_alloc();
    }
    p[0] = size;
    address = (void*)(&p[1]);
	
    return address;
}

对应的operator delete

 
void operator delete(void* address) {
    if (NULL == address)
	return;
    
    size_t* p = (size_t*)address;

    /* Get the size and do something else */
    /* size_t size = p[-1];               */

    void* p2 = (void*)(&p[-1]); 

    free(p2);
}

github: MemoryMonitor

Categories: C/C++

Tagged as:

lnmcc