Returning Char Pointer Without Heap

517 Views Asked by At

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.

3

There are 3 best solutions below

4
Neil Kirk On BEST ANSWER

Pointers can point to any variable, whether on the heap or stack. c_str returns 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.

2
Cornstalks On

The pointer returned by c_str() is actually an internal pointer into the memory of the buffer of the string (which has already been allocated on the heap). That's way it doesn't have to allocate any (new) memory. The memory has already been allocated and is how the string object stores its data.

That's why the pointer returned by c_str() is invalid after modifying the string: since it's pointing to an internal buffer, that buffer may no longer be valid after the manipulation.

The pointer obtained from c_str() may be invalidated by:

  • Passing a non-const reference to the string to any standard library function, or
  • Calling non-const member functions on the string, excluding operator[], at(), front(), back(), begin(), rbegin(), end() and rend().

Note that since C++11, c_str() and data() perform the same function, and it works similar to how std::vector's data() member works.

0
Thomas Matthews On

Here is an example of a function returning a pointer to something not no the heap or stack:

char const * Hello(void)
{
  static const char hello_text[] = "Hello";
  return &hello_text[0];
}

Because the variable was declared as static, the variable will exist after the execution leaves the function. Therefore, return a pointer to this value is perfectly valid.