malloc 和 free在结构体中的用法一个小疑问,该怎么解决
malloc 和 free在结构体中的用法一个小疑问
刚看了一个前人写的代码,结构体定义:
typedef struct t_sym {
char *sym_name; //- stores name of symbol
int type; //- stores type of symbol (mem vs. label)
int loc_val; //- local value of symbol
int glob_val; //- global value of symbol
int lineNum; //- line number where defined in original file
uchar sym_status; //- defined, not defined, multiply defined
struct t_sym *next; //- for the linked list thing
} sym_t;
他用malloc分配内存的函数中:
struct t_sym* Create_symItem(char* name, int type, int loc_val, int glob_val, int lineNum)
{
the_sym=(struct t_sym*)malloc(sizeof(struct t_sym));
}
而在删除的函数中
void Delete_symItem(sym_t *the_item)
{
if (the_item==NULL) return;
if (the_item-> sym_name!=NULL) {
free(the_item-> sym_name);
}
}
删除函数只是free了sym_t中的 sym_name, 如果不free整个sym_t是不是会引起内存泄漏?
或者说: 因为定义的这个结构体类型实际上是一个list, 在free的时候只要free这个list的入口即可,不用每个list元素都要free?
------解决方案--------------------
错
char *sym_name;sym_name是指针,其它参数都是常量,如果还有别的指针,也要求一并free
------解决方案--------------------
有一个malloc就要对应一个且仅一个free,自己根据这个原则判断吧。
------解决方案--------------------
想想C++里的类都是怎么处理的,你就明白了
类里面的析构函数负责释放成员申请的内存,
作为用户只要负责释放这个动态申请的对象就行了,
析构函数会帮你解决内部的东西
所以对于这个结构体来说,
malloc了一个sym_t,
如果它内部的那个指针sym_name也malloc了一块内存,
那在你释放这个结构体对像sym_t之前,
你一定先去释放它里面的sym_name,这样就不会内存泄露了
------解决方案--------------------
我觉得应该再free一下the_item
刚看了一个前人写的代码,结构体定义:
typedef struct t_sym {
char *sym_name; //- stores name of symbol
int type; //- stores type of symbol (mem vs. label)
int loc_val; //- local value of symbol
int glob_val; //- global value of symbol
int lineNum; //- line number where defined in original file
uchar sym_status; //- defined, not defined, multiply defined
struct t_sym *next; //- for the linked list thing
} sym_t;
他用malloc分配内存的函数中:
struct t_sym* Create_symItem(char* name, int type, int loc_val, int glob_val, int lineNum)
{
the_sym=(struct t_sym*)malloc(sizeof(struct t_sym));
}
而在删除的函数中
void Delete_symItem(sym_t *the_item)
{
if (the_item==NULL) return;
if (the_item-> sym_name!=NULL) {
free(the_item-> sym_name);
}
}
删除函数只是free了sym_t中的 sym_name, 如果不free整个sym_t是不是会引起内存泄漏?
或者说: 因为定义的这个结构体类型实际上是一个list, 在free的时候只要free这个list的入口即可,不用每个list元素都要free?
------解决方案--------------------
错
char *sym_name;sym_name是指针,其它参数都是常量,如果还有别的指针,也要求一并free
------解决方案--------------------
有一个malloc就要对应一个且仅一个free,自己根据这个原则判断吧。
------解决方案--------------------
想想C++里的类都是怎么处理的,你就明白了
类里面的析构函数负责释放成员申请的内存,
作为用户只要负责释放这个动态申请的对象就行了,
析构函数会帮你解决内部的东西
所以对于这个结构体来说,
malloc了一个sym_t,
如果它内部的那个指针sym_name也malloc了一块内存,
那在你释放这个结构体对像sym_t之前,
你一定先去释放它里面的sym_name,这样就不会内存泄露了
------解决方案--------------------
我觉得应该再free一下the_item