作为一个大的系统软件,如果避免内存泄露(memory leakage)是系统实现所面对的关键问题之一,Postgresql利用MemoryContext这个概念来解决这个问题,先来看看几个数据结构的定义:
typedef
struct MemoryContextMethods
{
void *(*alloc) (MemoryContext context,Size size);
/* call this free_p in case someone #define's free() */
void (*free_p) (MemoryContext context,void *pointer);
void *(*realloc) (MemoryContext context,void *pointer,Size size);
void (*init) (MemoryContext context);
void (*reset) (MemoryContext context);
void (*delete) (MemoryContext context);
Size (*get_chunk_space) (MemoryContext context,void *pointer);
bool (*is_empty) (MemoryContext context);
void (*stats) (MemoryContext context);
#ifdef MEMORY_CONTEXT_CHECKING
void (*check) (MemoryContext context);
#endif
} MemoryContextMethods;
typedef
struct MemoryContextData
{
NodeTag type; /* identifies exact kind of context */
MemoryContextMethods *methods; /* virtual function table */
MemoryContext parent; /* NULL if no parent (toplevel context) */
MemoryContext firstchild; /* head of linked list of children */
MemoryContext nextchild; /* next child of same parent */
char *name; /* context name (just for debugging) */
} MemoryContextData;