many compilers and loaders will assign strings simply declared as "a string" to read only persistent memory segments. Is there a way to determine this at runtime so as not to allocate duplicates when persistence is desired and one gets passed "const char *" arguments ? Also to prevent freeing them.
1 Answer
The generic answer is no. Not in a portable way.
So there isn't really a way to tell the difference when a (bad interface) function returns memory that is static or dynamically allocated. E.g.,
char* num_to_string(int number) {
static char buffer[5];
if(number < 10000) {
std::sprintf(buffer, "%d", number);
return buffer;
}
char* bigger_buffer = new char[50];
std::sprintf(bigger_buffer, "%d", number);
return bigger_buffer;
}
The use of the above function will be unable to (without looking at the implementatin) when he is repsonsible for cleaning up the memory returned.
-
The use case specifically for me is whether I need to do a strdup or use std::string as keys in a symbol table or just put the string in the map. as in symbol = table.add("symbolName");– peterkFeb 16, 2019 at 7:38
-
@peterk From your description, I'd go for
std::string
since it handles its own memory. Withstrdup
you are always responsible for the returned memory.– Bo RFeb 16, 2019 at 8:44 -
yes but useful in a case like an embedded system symbol table not to have to duplicate the memory usage, hence the question :)– peterkFeb 16, 2019 at 15:45
-
Well if using C++17 there's this hand alternative called
std::string_view
that can reuse memory.– Bo RFeb 16, 2019 at 15:47 -
free()
ordelete
.std::string_view
or other functions for dynamic memory management.