I was working on a program and I noticed something that didn't really make a lot of sense to me. std::string has a function called c_str() which returns a C-style string (NULL-terminated) representation of the std::string object. What does not make sense to me is how the c_str() function can return a const char * without allocating it to the heap. The function seemingly returns the char array on the stack.
I have always thought a function could only return a valid pointer if the value it pointed to was allocated on the heap using a function like malloc() or calloc().
How can c_str() return the string without using the heap and could I somehow mimic this same behavior in my own code?
Thank you all in advance.
Pointers can point to any variable, whether on the heap or stack.
c_strreturns a pointer to the string object's internal buffer. Usually this is on the heap, however some compilers, at their discretion, may place the data of small strings on the stack instead. How do you know, though, that the returned pointer is on the stack and not the heap?I'm not sure what exactly you want to mimic in your own code.