sel*_*sel 2 c malloc free pointers
假设我有一个结构:
typedef struct{
char *ID;
char *name;
float price;
int quantity;
} Generic_Properties;
Run Code Online (Sandbox Code Playgroud)
现在,如果我已经使用malloc为堆中的空间分配空间并将地址保存在指针中,那就让我打电话给他p1.现在我想释放那个特定的内存块,只需声明free(p1):
free(p1);
Run Code Online (Sandbox Code Playgroud)
或者我需要单独释放ID和名称指针,因为我使用malloc为他们指向的字符串分配空间?
Moh*_*ain 10
规则是,malloc并且free应该成对出现.免费所有东西malloc只需一次.
char name[] = "some_name";
Generic_Properties *p1 = malloc(...); /* 1 */
p1->ID = malloc(...); /* 2 */
p1->name = name;
...
...
/* free(p1->name); Don't do this, p1->name was not allocated with malloc*/
free(p1->ID); /* 2' */
free(p1); /* 1' */
/* if(p1 && p1->name[0] == '?') {} don't dereference p1 after it is freed. It is dangling now */
...
...
/* free(p1); don't free p1 again as it is already freed and is dangling. */
p1 = NULL;
free(p1); /* OK */
Run Code Online (Sandbox Code Playgroud)