I defined a structure for options in my config file and a pointer to this structure in "config.h" file and I read config file using libconfig and set values in function get_config() that is defined in file "config.c". In main function I initialize pointer to structure and call get_config() function. libconfig works well and prints values of structure's fields correctly but when I print same fields in main functions their values are incorrect!
"config.h"
#include <stdio.h>
#include <stdlib.h>
#include <libconfig.h>
typedef struct
{
int buffer_size;
const char * DBusername;
const char * DBpassword;
}conf;
conf *config;
int get_config();
"config.c"
#include "config.h"
int get_config()
{
config_t cfg;
config_setting_t *setting;
config_init(&cfg);
/* Read the file. If there is an error, report it and exit. */
if(! config_read_file(&cfg, "config.cfg"))
{
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, "buffersize", &config->buffer_size))
printf("buffersize: %d\n\n", config->buffer_size);
else
fprintf(stderr, "No 'buffersize' setting in configuration file.\n");
if(config_lookup_string(&cfg, "DBusername", &config->DBusername))
printf("DBusername: %s\n\n", config->DBusername);
else
fprintf(stderr, "No 'DBusername' setting in configuration file.\n");
if(config_lookup_string(&cfg, "DBpassword", &config->DBpassword))
printf("DBpassword: %s\n\n", config->DBpassword);
else
fprintf(stderr, "No 'DBpassword' setting in configuration file.\n");
config_destroy(&cfg);
return(EXIT_SUCCESS);
}
"store.c"
int main(){
config = (conf*) malloc(sizeof(conf));
if(get_config() == EXIT_FAILURE)
return 0;
printf("\n%s", config->DBusername);
printf("\n%s", config->DBpassword);
printf("\n%d", config->buffer_size);
}
The problem is because of defining char* in structure. I changed the char* to char[] and the problem is solved! :)