dir*_*tyb 1 c pointers memory-leaks dynamic-memory-allocation
我有以下结构:
typedef struct pair {
int *key; // search key for this item
int *count; // pointer to data for this item
struct pair *next; // children
} pair_t;
typedef struct counters {
struct pair *head;
} counters_t;
Run Code Online (Sandbox Code Playgroud)
我有以下功能:
static pair_t * // not visible outside this file
pair_new(const int key)
{
pair_t *pair = malloc(sizeof(pair_t));
free(pair->key);
free(pair->count);
if (pair == NULL) {
// error allocating memory for pair; return error
return NULL;
} else {
pair->key = malloc(sizeof(int));
pair->count = malloc(sizeof(int));
*(pair->key) = key;
*(pair->count) = 1;
pair->next = NULL;
return pair;
}
}
Run Code Online (Sandbox Code Playgroud)
注意我首先分配一对,检查内存是否正确分配,然后如果是,我将值分配给对的实例的元素.为了给这些元素赋值(键和计数),我必须为它们(元素)分配内存.后来在我的主程序中我调用了delete函数:
(ctrs是对的链表)
void counters_delete(counters_t *ctrs){
if(ctrs!=NULL){
pair_t *temp = ctrs->head;
while(temp!=NULL){
printf("freeing for key %d\n",*(temp->key));
free(temp->count);
free(temp->key);
temp = temp->next;
}
ctrs->head=NULL;
}
return;
}
Run Code Online (Sandbox Code Playgroud)
我释放每一对的钥匙和数量.
因为我分配了一对的完整大小,然后再次为每对的元素分配,我留下了在程序结束时尚未释放的内存.我怎样才能解决这个问题?
首先,删除
free(pair->key);
free(pair->count);
Run Code Online (Sandbox Code Playgroud)
之后malloc(),因为调用free()内存管理函数未返回的指针会调用未定义的行为.
也就是说,在开始时,你malloc()是原始变量和成员,最后,你只释放指针成员key和count结构变量,但实际变量temp仍然是分配的.这是导致泄漏的原因.
你也必须释放它temp.