Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
November 14, 2021 09:54 pm GMT

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

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!


Original Link: https://dev.to/baenencalin/is-there-a-way-to-convert-dynamically-allocated-memory-to-static-memory-or-copy-ptr-contents-in-cc-127d

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To