我正在学习《零基础学C编程》这个在线课程。在下面的代码示例中,我不明白为什么需要两个free()
调用。我认为只需要调用free()
一次,因为只有一个malloc()
。请问为什么我们需要两个?
如果我注释掉free(who->name);
,那么valgrind
会告诉我我失去了一块内存,就像这样:
LEAK SUMMARY:
definitely lost: 21 bytes in 2 blocks
以下是代码:
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
struct Person {
char *name;
int age;
int height;
int weight;
};
struct Person *Person_create(char *name, int age, int height, int weight)
{
struct Person *who = malloc(sizeof(struct Person));
assert(who != NULL);
who->name = strdup(name);
who->age = age;
who->height = height;
who->weight = weight;
return who;
}
void Person_destroy(struct Person *who)
{
assert(who != NULL);
free(who->name); /* Why this one??! */
free(who);
}
int main(int argc, char *argv[])
{
// make two people structures
struct Person *joe = Person_create(
"Joe Alex", 32, 64, 140);
struct Person *frank = Person_create(
"Frank Blank", 20, 72, 180);
// destroy them both so we clean up
Person_destroy(joe);
Person_destroy(frank);
return 0;
}
strdup
不是标准C函数,但它在POSIX中。除了malloc
、calloc
和realloc
之外,没有标准C函数会返回需要释放的指针。 - M.M