首页 > 解决方案 > win32 memory cache impliment when reallocate the memory size

问题描述

I'm trying imply a databuffer, the data all have been convert into text format, each field end with ascii code '\0'. It could be a lot of columns and rows. It may not alter during the presentation (for the frant ui display). It should be very easy to store into the memory cache , and be easy to get the value (hope do not cost too many time and please consider the buffer size).

So I'm tring and then the terrible data structure comes:

//first mem cache max size.
#define FIRST_MEM_MAXSIZE 10*1024*1024
//define operation function plt;.
typedef struct __MASS_DATA_MEM__ {
    //interface for access.
    int* off_index;//offset for each item. when initialize, allocate a offset array store each item offset.
    int col;//valid columns count;
    int row;//valid rows count;
    
    //internal structure.
    char* mem; // mem cache.
    int cur_index; //current item index 
    char* cur_plt;//current mem pointer.

}RMassMem,*pMassMem;
pMassMem InitialMassMem(int cols,int rows);
int ReAllocMem(pMassMem mem);
int ReleaseMassMem(pMassMem mem);
int AddMemItem(pMassMem mem,char* text);
const char* GetMemItem(pMassMem mem,int row,int col);

I want to be more flexibility , the problem is the ReAllocMem function. It's bad.very bad. realloc cost time , not mention the fragment of memory. What the real cache do to expend its size ? A real one , simple one ?

int ReAllocMem(pMassMem mem)
{
    int result_code=-1;
    //consider the current items
    size_t curr_size=0;
    int offset=0;    
    
    if(!mem) goto _mem_realloc_exit;
    
    curr_size=_msize(mem->mem)/sizeof(char);
    offset=mem->cur_plt-mem->mem;
    
    mem->mem=(char*)realloc(mem->mem,curr_size+FIRST_MEM_MAXSIZE);
    if(!mem->mem) {
        MessageBox(NULL,"ReAllocMem:mem cache failed","Serious trouble",MB_OK|MB_ICONINFORMATION);
        goto _mem_realloc_exit;
    }
        
    mem->row+=mem->row;
    mem->off_index=(int*)realloc(mem->off_index,sizeof(int)*mem->row*mem->col);
    if(!mem->off_index) {
        MessageBox(NULL,"ReAllocMem:offset cache failed","Serious trouble",MB_OK|MB_ICONINFORMATION);
        goto _mem_realloc_exit;
    }
    
    mem->cur_plt=mem->mem+offset;
    
    result_code=0;
_mem_realloc_exit:
    if(result_code!=0) {
        ReleaseMassMem(mem);
    }
    return result_code;
}

标签: c

解决方案


推荐阅读