0

I am using the libconfig library to read some configuration data from a file. I am having trouble extracting out the function for parsing the information and cleaning up afterwards.

Running strcpy(*hostname, tmp) causes a core dump.

hostname, port, and ip are initialized to NULL.

int parseConfig(char **hostname, char **port, char **ip) {

    config_t cfg, *cf;
    const char *tmp;

    cf = &cfg;
    config_init(cf);

    if(!config_read_file(cf, CONFIG)) {
        fprintf(stderr, "%s:%d - %s\n",
            config_error_file(cf),
            config_error_line(cf),
            config_error_text(cf));
        config_destroy(cf);
        return(EXIT_FAILURE);
    }

    config_lookup_string(cf, "hostname",  &tmp);
    strcpy(*hostname, tmp);
    config_lookup_string(cf, "ip", &tmp);
    strcpy(*ip, tmp);
    config_lookup_string(cf, "port", &tmp);
    strcpy(*port, tmp);

    config_destroy(cf);

    return(EXIT_SUCCESS);
}
4

2 回答 2

3

由于它们被初始化为 NULL,因此您应该为它们分配足够的内存空间。

config_lookup_string(cf, "hostname",  &tmp);
*hostname = malloc(strlen(tmp)+1);
strcpy(*hostname, tmp);
config_lookup_string(cf, "ip", &tmp);
*ip = malloc(strlen(tmp)+1);
strcpy(*ip, tmp);
config_lookup_string(cf, "port", &tmp);
*port = malloc(strlen(tmp)+1);
strcpy(*port, tmp);

或者,如果你strdup()有空,

config_lookup_string(cf, "hostname",  &tmp);
*hostname = strdup(tmp);
config_lookup_string(cf, "ip", &tmp);
*ip = strdup(tmp);
config_lookup_string(cf, "port", &tmp);
*port = strdup(tmp);
于 2015-08-27T07:08:18.177 回答
0

砍掉中间人。

config_lookup_string(cf, "hostname",  hostname);

这要求您永远不要 destroy cfg,因为它拥有为配置字符串分配的内存。

static config_t cfg;
config_t *cf;

// config_destroy(cf); <-- don't!

如果每次程序运行只读取一次配置,这应该不是问题。

于 2015-08-27T07:16:37.783 回答