在C中分配内存混淆

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?

谢谢

Cha*_*via 6

调用malloc(sizeof(struct some_struct));为您的结构提供内存,包括两个整数字段和指针字段的空间.

但是,指针字段在指向内存中的有效位置之前不能使用.为此,您需要将其指向有效的内存位置,例如为其分配内存malloc或将其指向预先存在的有效内存位置:

例如:

test_struct->some_string = malloc(100); // Allocate 100 bytes for the string
Run Code Online (Sandbox Code Playgroud)

  • @chutsu,你用`malloc`分配的任何东西都必须用`free()`释放.所以如果你使用`malloc`为`test_struct-> some_string`分配内存,那么你也必须用`free`释放它.但是在您的示例代码中,您只需将`test_struct`设置为字符串文字,这意味着您不需要释放它. (2认同)