Skip navigation

Category Archives: memory_management

My first language was Java, and though I’ve been working with C++ for a bit now certain things still trip me up now and again.  While working on a class that tokenizes std::string objects based on std::string delimiters, I came across the use-case of wanting to modify char data returned from a string’s c_str() method.  Since this returns a const char* I tried

char* cstr = myStr.c_str();

but that throws a compiler error because it attempts the quite rightly illegal conversion between a const pointer and a mutable one.  In Java the idiom above re-implemented as below would be legal

final String testS = "final";
String testS2 = testS;
testS2 = "mutable";

This is legal in Java only because Java allocates new memory space for testS2 and copies the content of testS into it behind the scenes.  testS remains immutable while testS2 is mutable.  One simple way to obtain the same result in C/C++ is via strncpy() as follows:

std::string myString = "Hello"

const char* cstr_final = myString.c_str();

char cstr_mut[sizeof(cstr_final)];


With that cstr_mut is a fully modifiable clone of the content pointed to by cstr_final 🙂

side note: its obvious from my other posts that I enjoy including pictures– I have to advise against entering the search query “c string” in google image search while at work as it seems that there is an article of particularly risque lingerie by that name  *facepalm*


Seg Fault

Causal factors unclear

Dump step