This content originally appeared on DEV Community and was authored by Calin Baenen
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 isType_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!
This content originally appeared on DEV Community and was authored by Calin Baenen
Calin Baenen | Sciencx (2021-11-14T21:54:03+00:00) Is there a way to convert dynamically allocated memory to static memory OR copy ptr contents in C/C++?. Retrieved from https://www.scien.cx/2021/11/14/is-there-a-way-to-convert-dynamically-allocated-memory-to-static-memory-or-copy-ptr-contents-in-c-c/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.