chu*_*tsu 3 c memory malloc struct
我已经做了很多环顾四周,但仍然无法理解它,让我说我有结构:
struct some_struct {
int x;
int y;
char *some_string;
};
Run Code Online (Sandbox Code Playgroud)
可以说我们有上面的结构,你会如何为上面的结构分配一些内存?人们可以简单地做到:
struct some_struct *test_struct;
test_struct = malloc(sizeof(struct some_struct));
Run Code Online (Sandbox Code Playgroud)
但这够了吗?你不需要为内存分配一些内存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";
Run Code Online (Sandbox Code Playgroud)
以下代码是否足以释放分配的内存?
free(test_struct);
Run Code Online (Sandbox Code Playgroud)
或者我是否必须进入并释放char*some_string?
谢谢
调用malloc(sizeof(struct some_struct));为您的结构提供内存,包括两个整数字段和指针字段的空间.
但是,指针字段在指向内存中的有效位置之前不能使用.为此,您需要将其指向有效的内存位置,例如为其分配内存malloc或将其指向预先存在的有效内存位置:
例如:
test_struct->some_string = malloc(100); // Allocate 100 bytes for the string
Run Code Online (Sandbox Code Playgroud)