曾经以为自己很好的了解了指针数组与指针的指针,而最近出现的一个BUG 让我不得不又重新认识了一下,
简单事简单说;
typedef structd _section section;
struct _option{
char *name;
char *value;
}
struct _section{
char *name;
struct _options options**;//_options *options[] 写成指针数组的话就是这个样子了
};
struct _appcfg{
int count;
section **sections;
}
这是读取配置文件中的一个结构。配置文件由配置项sections和options组成,每个section包含一个或者多个option
_section中包含的options便是具体的配置项。
代码基本结构如下
struct _appcfg appcfg;
.....
appcfg.sections = malloc(count);
大家别不相信,这真的是我写的。gcc编译也没出问题,警告都没有!!
并且在相当长一段时间内都没有发现有什么不妥。原因就是我的配置项section从来没多于3个,呵呵,这个可是最关键的哦。
直到有一天,我的配置文件突然多了很多的section,BUG终于出来了。
现象如下:
1.可以正常访问,数据没什么不对
2.三个section没有问题,四个section以上,free时发生“double free”错误。
当中原因呢,看了文章的自己想想。我就不多说了,只写目前没有问题的写法
appcfg.sections = (section **)malloc(count * sizeof(section *));
简单事简单说;
typedef structd _section section;
struct _option{
char *name;
char *value;
}
struct _section{
char *name;
struct _options options**;//_options *options[] 写成指针数组的话就是这个样子了
};
struct _appcfg{
int count;
section **sections;
}
这是读取配置文件中的一个结构。配置文件由配置项sections和options组成,每个section包含一个或者多个option
_section中包含的options便是具体的配置项。
代码基本结构如下
struct _appcfg appcfg;
.....
appcfg.sections = malloc(count);
大家别不相信,这真的是我写的。gcc编译也没出问题,警告都没有!!
并且在相当长一段时间内都没有发现有什么不妥。原因就是我的配置项section从来没多于3个,呵呵,这个可是最关键的哦。
直到有一天,我的配置文件突然多了很多的section,BUG终于出来了。
现象如下:
1.可以正常访问,数据没什么不对
2.三个section没有问题,四个section以上,free时发生“double free”错误。
当中原因呢,看了文章的自己想想。我就不多说了,只写目前没有问题的写法
appcfg.sections = (section **)malloc(count * sizeof(section *));