【发布时间】:2016-11-23 14:03:37
【问题描述】:
我有以下结构:
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;
我有以下功能:
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;
}
}
请注意,我首先为 pair 分配,检查内存是否正确分配,如果是,我将值分配给 pair 实例的元素。为了给这些元素(键和计数)赋值,我必须为它们(元素)分配内存。稍后在我的主程序中,我调用了删除函数:
(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;
}
其中我释放了每对的密钥并计数。
因为我分配了一对的完整大小,然后再次为每对的元素分配,所以我留下了在程序结束时尚未释放的内存。我该如何解决这个问题?
【问题讨论】:
-
为什么malloc后面有
free(pair->key); free(pair->count);? -
^^^^^^ ... 调用未定义的行为,因为这些指针是不确定的。
-
@WhozCraig Right 先生,已经将其转换为答案。 :)
-
@SouravGhosh.. 已经被上调 =)
-
有什么理由不让
key和count简单地ints?
标签: c pointers memory-leaks dynamic-memory-allocation