I am using the libconfig
library to read some configuration data from a file. I am having trouble extracting out the function for parsing the information and cleaning up afterwards.
Running strcpy(*hostname, tmp)
causes a core dump.
hostname
, port
, and ip
are initialized to NULL
.
int parseConfig(char **hostname, char **port, char **ip) {
config_t cfg, *cf;
const char *tmp;
cf = &cfg;
config_init(cf);
if(!config_read_file(cf, CONFIG)) {
fprintf(stderr, "%s:%d - %s\n",
config_error_file(cf),
config_error_line(cf),
config_error_text(cf));
config_destroy(cf);
return(EXIT_FAILURE);
}
config_lookup_string(cf, "hostname", &tmp);
strcpy(*hostname, tmp);
config_lookup_string(cf, "ip", &tmp);
strcpy(*ip, tmp);
config_lookup_string(cf, "port", &tmp);
strcpy(*port, tmp);
config_destroy(cf);
return(EXIT_SUCCESS);
}
Since they were initialized to NULL, you should allocate enough memory space for them.
config_lookup_string(cf, "hostname", &tmp);
*hostname = malloc(strlen(tmp)+1);
strcpy(*hostname, tmp);
config_lookup_string(cf, "ip", &tmp);
*ip = malloc(strlen(tmp)+1);
strcpy(*ip, tmp);
config_lookup_string(cf, "port", &tmp);
*port = malloc(strlen(tmp)+1);
strcpy(*port, tmp);
Or, if you have strdup()
available,
config_lookup_string(cf, "hostname", &tmp);
*hostname = strdup(tmp);
config_lookup_string(cf, "ip", &tmp);
*ip = strdup(tmp);
config_lookup_string(cf, "port", &tmp);
*port = strdup(tmp);