2015-02-08 66 views
0

我正在为某个项目工作INI风格的配置解析器,并且我遇到了下一个麻烦。 我有3层结构:在周期中为结构内的struct分配内存

typedef struct { 
    const char* name; 
    unsigned tract; 
    int channel; 
    const char* imitation_type; 
} module_config; 

typedef struct { 
    int channel_number; 
    int isWorking; 
    int frequency; 
    int moduleCount; 
} channel_config; 

typedef struct { 
    int mode; 
    module_config* module; 
    channel_config* channel; 
} settings; 

我有函数来处理我的INI文件数据(我下inih解析器工作):粘贴到pastebin原因太长。最后,在main()中,我做了下一个:

settings* main_settings; 
main_settings = (settings*)malloc(sizeof(settings)); 
main_settings->module = (module_config*)malloc(sizeof(module_config)); 
main_settings->channel = (channel_config*)malloc(sizeof(channel_config)); 
if (ini_parse("test.ini", handler, &main_settings) < 0) { 
    printf("Can't load 'test.ini'\n"); 
    return 1; 
} 

结果,二进制崩溃与内存错误。我认为(不,我知道),我在处理程序()中错误地分配了内存,但我不明白,我在哪里做错了。我花了整晚的时间试图理解内存分配,而且我很累,但现在我只是有趣的是,我做错了什么,以及如何强制这个工作正常。 P.S.对不起,丑陋的英语

+0

为什么不只是存储第3内侧的两个结构中,没有指针?指针间接似乎没有必要。 – 2015-02-08 05:04:25

+0

标记为“不清楚你在问什么”。 – Barracuda 2015-02-08 05:15:15

+0

@JohnZwinck导致模块和通道数量可以是任何。因此,我也动态地分配内存给主模块和通道 – 2015-02-08 05:40:20

回答

0

的问题似乎与您的结构重新分配:

所有的
pconfig = (settings *) realloc(pconfig, (module_count + channel_count) * sizeof(channel_config)); 
pconfig->module = (module_config *) realloc(pconfig->module, module_count * sizeof(module_config)); 
pconfig->channel = (channel_config *) realloc(pconfig->channel, channel_count * sizeof(channel_config)); 

首先,你不能重新分配的主要设置结构。由于您的处理程序将始终使用原始值pconfig进行调用,因此modulechannel数组的重新分配无效,您将访问释放的内存。

而且再分配modulechannel阵列时,你应该分配count + 1元素,因为handler下一次调用可以分配到[count]插槽。

所以尝试更换上面的三条线:

pconfig->module = (module_config *) realloc(pconfig->module, (module_count + 1) * sizeof(module_config)); 
pconfig->channel = (channel_config *) realloc(pconfig->channel, (channel_count + 1) * sizeof(channel_config)); 
+0

另请注意,将realloc()的结果赋值给它的第一个参数总是一个坏主意,因为当realloc()失败时会导致内存泄漏。 – 2015-02-08 11:34:50