Is there a way to convert dynamically allocated memory to static memory OR copy ptr contents in C/C++?

Calin Baenen - Nov 14 '21 - - Dev Community

For reference, static memory is memory that is memory that is assigned, managed, and freed for you (an example is char const* str = "Hello World!";).
C/C++ will clean that string up for you.

Dynamically allocated memory is memory you request, manage, and must clean yourself (an example is Type_t* array = malloc( sizeof(Type_t)*arrLength );).

I'm messing around with C strings in C++, even testing ideas for my own String type. - And I was creating a String +(char c) method, when I thought of something: "How can I return a String object whose str property is statically allocated, and not dynamically allocated?".
Since the only method of adding a character to an immutable string I can think of involves using malloc( (oldStrLen+1)*sizeof(char) ), which is dynamically allocated.

So, is there a way I can copy the contents of a pointer to a new statically allocated pointer, or convert dynamically allocated memory to statically allocated memory in C/C++?

Thanks!
Cheers!

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .