I want to initialize a program with some configuration data. It receives them as an url-encoded json via argv[], decodes and deserializes them and hand them to a method inside a class, that is supposed to set the relevant variables to the submitted values.
The variables have the type c-string, so i do the conversion first before assigning the values to the variables declared outside the method. If reading out those newly set values from the pointers, everything is fine, as long as i am staying inside this method. Upon leaving it, the variables with their values set from the handed configuration data do contain garbage only, while the one filled from the string literal is perfectly ok.
I printed out information about the variables type (typeid().name()). While they are not necessarily human readable, comparison between shows, that they all are of the type they are supposed to be. Next is compared the values of the pointers inside and out side the method - they were the same.
/* Config.cpp */
using json = nlohmann::json;
const char *Config::DB_HOST;
const char *Config::DB_USER;
const char *Config::DB_PASSWORD;
const char *Config::DB_NAME;
const char *Config::DB_SOCK;
Config::Config() {}
void Config::initDB(json dbConfig) {
string host = dbConfig["host"];
DB_HOST = host.c_str();
string user = dbConfig["user"];
DB_USER = user.c_str();
string pass = dbConfig["pass"];
DB_PASSWORD = pass.c_str();
string name = dbConfig["name"];
DB_NAME = name.c_str();
DB_SOCK = "/var/run/mysqld/mysqld.sock";
}
I am especially puzzled about the differences between the values set by the variables and the value set by the string literal. The first fails, the latter works. Whats the difference between them? After some reading in the forum i had the understanding, c_str() should return exactly the same data type (a null-terminated pointer to the data) as the literal.
Thanks for your hints!