Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread safety of c_str() in C++

I have created a class, SettingsClass that contains static strings that hold db connection strings to be used by the MySQL C++ connector library (for e.g. hostname, dbname, username, password).

Whenever a function needs to connect to the database, it calls the .c_str() function on these static strings. For example:

Class SettingsClass
{
    public:
    static string hostname;
    ...
}SettingsClass;
string SettingsClass::hostname;

//A function that needs to connect to the DB uses:
driver = get_griver_instance();
driver->connect(SettingsClass.hostname.c_str(),...);

The static strings are populated once in the process lifetime. Its value is read from a configuration file.

My application is multithreaded. Am I using c_str() in a safe way?

like image 622
Cik Avatar asked Dec 28 '12 16:12

Cik


1 Answers

The c_str() in itself should be threadsafe. However, if you have another thread that accesses (writes to) the string that you are taking c_str() of, then you're playing with matches sitting in a pool of petrol.

Typically c_str() is implemented by adding a zero value (the null character 0x00, not the character for zero which is 0x30) on the end of the existing string (if there isn't one there already) and passes back the address of where the string is stored.

Anyone interested can read the libstdc++ code here: libstdc++, basic_string.h The interesting lines are 1802 and 294 - 1802 is the c_str() function, and 294 is the function that c_str() calls.

like image 61
Mats Petersson Avatar answered Nov 06 '22 19:11

Mats Petersson