1

I'm using libconfig.h to read parameters from a configuration file, but I've problems printing values inside/outside a function.

example.h

int get_config();

example.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;
}

The value of myInt printed inside/outside get_config() is the same. For myString, the call in main() return spurious chars, different from what printed before.

What's wrong?

4

1 回答 1

1

libconfig 手册

config_lookup_string() 返回的字符串的存储由库管理,并在设置被销毁或设置值更改时自动释放;调用者不得释放该字符串。

config_t cfg是本地的,get_config并且在离开该功能后超出范围。cfg这意味着(a)您以后无法正确清理,config_destroy()并且(b)内部的任何引用都cfg可能无法访问,因为堆栈空间已被覆盖。

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

另一种方法是在程序执行期间cfg本地化并使其保持活动状态。main传递&cfgtoget_config作为指针并cfg在从返回之前销毁main。在这种情况下,只要字符串有效,字符串就会cfg有效。

于 2014-10-16T10:54:21.827 回答