【发布时间】:2012-12-13 03:01:19
【问题描述】:
我已经环顾四周,但仍然无法理解它,假设我有结构:
struct some_struct {
int x;
int y;
char *some_string;
};
假设我们有上面的结构,你会如何为上面的结构分配一些内存? 可以简单地做:
struct some_struct *test_struct;
test_struct = malloc(sizeof(struct some_struct));
但这足够了吗?您不需要为some_string 分配一些内存吗?或者如果结构体包含更多的指针,你是否也不需要为它们分配内存?
编辑:还有一件事……假设我的结构 some_struct 已经有数据,例如
struct some_struct *test_struct = malloc(sizeof(some_string);
test_struct->x = 2;
test_struct->y = 3;
test_struct->some_string = "sadlfkajsdflk";
以下代码是否足以释放分配的内存?
free(test_struct);
还是我也必须进去释放 char* some_string?
谢谢
【问题讨论】:
-
关于编辑,你让
test_struct->some_string指向一个字符串文字,而不是指向内存(m|c|re)alloced,所以在这种情况下你不应该free它。但是如果你有(m|c|re)alloced内存到test_struct->some_string,你应该在freeingtest_struct之前free它,否则你会泄漏内存。