I'm building a big piece of inherited code that uses OpenLDAP extensively, and now that we're (trying to) switch to FreeBSD 7.0, GCC complains quite a bit more than before:
43 modFormat.mod_op = LDAP_MOD_ADD; 44 modFormat.mod_type = "rocketseedFormat"; 45 vformat[0] = "2"; 46 vformat[1] = NULL; 47 modFormat.mod_values = vformat;
rscode/rocketutil/mydap.cpp:44: warning: deprecated conversion from string constant to 'char*' rscode/rocketutil/mydap.cpp:45: warning: deprecated conversion from string constant to 'char*'
Are we risking some sort of free()-based crashes by populating the struct with string constants? I grepped for mod_type in the OpenLDAP source and couldn't find any explicit dependency on the strings being dynamically allocated (except for ldap_mods_free(), which we don't call). That doesn't mean there exists no such dependency!
Would it be safe to const_cast<char *> the string constants, or will I need to wrap each with a strdup() and ldap_mods_free() it all after we're done?
Thanks
Bernd Jendrissek writes:
44 modFormat.mod_type = "rocketseedFormat"; 45 vformat[0] = "2"; (...) rscode/rocketutil/mydap.cpp:44: warning: deprecated conversion from string constant to 'char*' rscode/rocketutil/mydap.cpp:45: warning: deprecated conversion from string constant to 'char*'
Are we risking some sort of free()-based crashes by populating the struct with string constants?
No. You built the structure, you clean it up.
Would it be safe to const_cast<char *> the string constants,
Yes.
or will I need to wrap each with a strdup() and ldap_mods_free() it all after we're done?
No. ldap_mods_free() is just a helper function you could use if you did build the structure with malloc and strdup. Or better yet, with ber_memalloc and ber_strdup. (These are wrappers needed on Windows or something because IIRC memory must be freed by the same DLL which allocated it.)
This is just a case of "const poisoning" - once you slap a "const" at a declaration, it can easily spread out, demanding "const"s elsewhere too. C started out without "const", even on string literals (which may not be modified). C libraries and programs do tend to grow more consts over the year, but C++ has gone much farther. For one thing, because it has features like const_cast<> and mutable which make unwanted consts less painful.
When defining a library data structure, one has to decide on things like what to constify. The API has no reason to assume that the data is intended to be const - in fact, ldap_mods_free() would look strange if it was. Stranger than in C++, anyway.
openldap-software@openldap.org