0
votes

I can't retrieve the user value from my config file using C and libconfig.

configreader.h

#include <stdio.h>
#include <string.h>
#include <libconfig.h>
#ifndef CONFIGREADER_H_INCLUDED
#define CONFIGREADER_H_INCLUDED

char *userreader(){
    static const char *inputfile = "/opt/plaininc/config/handler.conf";
    config_t configreader;
    const char *userconfig;
    if(! config_read_file(&configreader, inputfile)){
        config_destroy(&configreader);
        exit(EXIT_FAILURE);

    }
    if (config_lookup_string(&configreader, "handler.user", &userconfig)){
        config_destroy(&configreader);
        return userconfig;

    } else {
        config_destroy(&configreader);
        exit(EXIT_FAILURE);

    }
}

#endif

CONFIG.c

    #include <stdio.h>
#include <stdlib.h>
#include "configreader.h"

int main(){
    const char *user = userreader();
    printf("%s", user);
}

GDB:

Program received signal SIGSEGV, Segmentation fault. 0xb7e63496 in free () from /lib/i386-linux-gnu/libc.so.6

1
What does config_destroy do?tkausl
Why is there a function in the header file? And please include all the code needed to reproduce the errorUnh0lys0da
@tkausl config_destroy() destroys the configuration config, deallocating all memory associated with the configuration, but does not attempt to deallocate the config_t structure itself.Luís Duarte
Apparantly config_destroy() assumes the configreader is located on the heap. So you should do: config_t *configreader = malloc(sizeof(config_t)); Currently your configreader is on the stack so it makes no sense to deallocate it, since that would happen upon returning from the functionUnh0lys0da
[link] (pastebin.com/HXh9d6iR) @Unh0lys0da I tried that.Luís Duarte

1 Answers

2
votes

You need to initialize configreader using config_init(). Do:

config_t configreader;
const char *userconfig;
config_init(&configreader);
....