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?