采用这种结构:
typedef struct{
char *var;
} EXAMPLE;
请记住,当你的结构分配空间,你只为char *
指针分配空间。这个指针只是指向其他地方的内存。当你结构体free()
时,你只是释放了指针char *
,而不是它指向的实际内存。
因此,如果你把这个结构,然后串malloc()
空间,你想var
指向,你需要free()
字符串以及free()
荷兰国际集团的结构。
一些代码,演示如何这可能工作:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct {
char *var;
} EXAMPLE;
int main(int argc, char *argv[]) {
// malloc() space for the EXAMPLE struct.
EXAMPLE *point = malloc(sizeof(EXAMPLE));
// malloc() space for the string that var points to.
point->var = malloc(20 * sizeof(char));
// Copy "Hello!" into this memory (care with strcpy).
strcpy(point->var, "Hello!");
// Print it, it works!
printf("point->var is: %s\n", point->var);
// Free stuff.
free(point->var);
free(point);
return 0;
}
还要注意的是,我们不投的malloc()
的结果是,你并不意味着℃。另外请注意,我们free()
point-> var之前的第一个点。这很重要,因为如果我们首先指向free()
,我们会失去指向point-> var的指针,并且存在内存泄漏。
这不是有效的C代码。 – AnT
我不知道为什么,但是当我提交这个问题时,它删除了星号 –
'free'释放了作为产生其参数值的调用结果分配的内存。而已。不多也不少。 –