Is it possible to create class String without using heap in C++?

1.6k Views Asked by At

I would like to write me own class String which will have interface similar to std::string. String class shall not use dynamic memory allocation.

I need to have a c-tor:

String(char* ptrToFirstCharInTab, char* ptrToLastElementInTab);

And there should be tab which contains different (not know) number of element, so I do not know size while compiling.

In my opinion it's impossible, because if we do not know size of our array before compilation we can not create it without dynamic allocation - of course creating buffer for 500 char and then String class can be only 500 it' not my expections.

Do you have any idea? Maybe is any way to create buffor wchich I will shrink to fit? Thanks for help!

3

There are 3 best solutions below

9
On BEST ANSWER

You asked:

Is it possible to create class String without using heap in C++?

In fact, yes, it possible to dynamicly allocate memory on the stack by using _alloca or similiar platform dependent function. See this other answer for more details: C++ How to allocate memory dynamically on stack?

I would recommend against it and be absolutely sure that was the best alternative before commencing.

Update: I created an example with inlined constructer for demonstration purpose using gcc:

Compiler explorer Link: https://godbolt.org/z/M1F5VD

Full code:

#include <alloca.h>

struct String {
  __attribute__((always_inline)) inline String(size_t size) {
     bytes= static_cast<char*>(alloca( size ));// alloca() memory gets allocated here
  }
  char* bytes;
};

int workWithString( ) 
{
   //std::string teststr("test");
   String mystrclass(1000);
   mystrclass.bytes[0] = 'a';
   mystrclass.bytes[1] = 0;
   return 0;
}  // alloca() memory only gets freed here



int main() {
    return workWithString();
   }
0
On

I'm a bit confused with your question. You want to have std:: string without a heap and without size restrictions. Sorry to bring this to you: you can't have infinite memory.

If you have an pool of memory you want to dedicate to strings without it being fixed size for each string, an allocator can do so. The default allocator for the containers does new, however you can replace it without having to duplicate the internals of string.

7
On

You asked:

Do you have any idea? Maybe is any way to create buffor wchich I will shrink to fit?

In theory, yes you can. You can use a pre-allocated buffer as your heap memory. However, you'll have to write your own code to manage that buffer. Doable but not something I would recommend.