0

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

alk
  • 69,737
  • 10
  • 105
  • 255
Luís Duarte
  • 39
  • 1
  • 7
  • What does `config_destroy` do? – tkausl Dec 01 '17 at 14:23
  • Why is there a function in the header file? And please include all the code needed to reproduce the error – Unh0lys0da Dec 01 '17 at 14:24
  • @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 Dec 01 '17 at 14:24
  • 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 function – Unh0lys0da Dec 01 '17 at 14:27
  • [link] (https://pastebin.com/HXh9d6iR) @Unh0lys0da I tried that. – Luís Duarte Dec 01 '17 at 14:34
  • I don't know what you tried, but it tries to free something that is not in the heap. – Unh0lys0da Dec 01 '17 at 14:38

1 Answers1

2

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

config_t configreader;
const char *userconfig;
config_init(&configreader);
....
P.P
  • 117,907
  • 20
  • 175
  • 238