使用 libconfig 读取配置时出现 SIGSEGV
SIGSEGV when reading config with libconfig
我无法使用 C 和 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
您需要使用 config_init()
初始化 configreader
。做:
config_t configreader;
const char *userconfig;
config_init(&configreader);
....
我无法使用 C 和 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
您需要使用 config_init()
初始化 configreader
。做:
config_t configreader;
const char *userconfig;
config_init(&configreader);
....