c - 使用 libconfig.h 的字符串和字符集问题

标签 c struct config libconfig

我正在使用 libconfig.h 从配置文件中读取参数,但在函数内部/外部打印值时遇到问题。

例子.h

int get_config();

例子.c

#include <stdio.h>
#include <stdlib.h>
#include <libconfig.h>
#include "example.h"

typedef struct Conf{
    int myInt;
    const char *myString;
}Conf;

#define CONFIGFILE "./my.conf"
Conf *config;


int get_config(){
    config_t cfg;
    config_init(&cfg);

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

    if(config_lookup_int(&cfg,"myInt", &config->myInt)){
        printf("myInt = %d\n", config->myInt);
    }

    if(config_lookup_string(&cfg,"myString", &config->myString)){
        printf("myString = %s\n", config->myString);
    }

    config_destroy(&cfg);
    return 0;
}

int main(){
    config = (Conf*) malloc(sizeof(Conf));
    if(get_config() == EXIT_FAILURE){
        return 0;
    }
    get_config();

    printf("myInt = %d\n",config->myInt);
    printf("myString = %s\n",config->myString);

    return 0;
}

get_config() 内部/外部打印的 myInt 的值是相同的。对于 myStringmain() 中的调用返回虚假字符,与之前打印的不同。

怎么了?

最佳答案

来自libconfig manual :

Storage for the string returned by config_lookup_string() is managed by the library and released automatically when the setting is destroyed or when the setting's value is changed; the string must not be freed by the caller.

您的 config_t cfgget_config 的本地文件,在离开该函数后超出范围。这意味着 (a) 您不能稍后使用 config_destroy() 正确清理 cfg 和 (b) cfg 中的任何引用可能无法访问,因为堆栈空间已被覆盖。

您可以在 get_config 中使用 strdup 复制字符串。在这种情况下,在 get_config 结束时销毁 cfg,就像您 fclose 任何打开的本地文件一样。稍后还要注意 free 您的字符串。

另一种方法是使 cfg 成为 main 的本地,并在程序执行期间保持它处于事件状态。将 &cfg 作为指针传递给 get_config,并在从 main 返回之前销毁 cfg。在这种情况下,只要 cfg 有效,字符串就有效。

关于c - 使用 libconfig.h 的字符串和字符集问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26401882/

相关文章:

c - 自引用 C 结构

c - 如何将结构成员存储为大端

plugins - 如何使用Gradle选择正确的配置文件?

c# - c#中的配置文件

c - 参数类型不兼容且未在此函数中初始化

c - 从图像中提取较小的图像

c++ - C++ 中的结构填充

c++ - printf() 中 %f 和 %F 的区别?

php-从表中读取数据到数组中并检查条件

python - Configparser 整数