1
void foo(const char* s) { }
foo("bar");
  1. Where is the memory bar deallocated?
  2. What is the most comfortable and memory leak free practice to work with anonymous strings in function arguments? (I know there should be no magic strings, just curious.)
Jan Turoň
  • 31,451
  • 23
  • 125
  • 169
  • 3
    In c++ you should use std::string instead of char * – Sergey Miryanov Jul 18 '12 at 08:05
  • Is there any benefit from using the wrapper class here? – Jan Turoň Jul 18 '12 at 08:07
  • 1
    There are several SO questions pertaining to this topic. Apparently in most common architectures, the string literal is compiled directly into the DATA segment and is loaded according to the paging rules of your host OS [http://stackoverflow.com/questions/2589949/c-string-literals-where-do-they-go] [http://stackoverflow.com/questions/1971183/when-does-c-allocate-deallocate-string-literals] – nurettin Jul 18 '12 at 08:10

3 Answers3

4

In your example, the argument is a string literal, which has static lifetime, and is never deleted.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
2

"bar" is defined in the data section and the address will replace it in all the places you have it. The foo function will be called with a pointer to that address.

Chefire
  • 139
  • 1
  • 7
1

The memory for bar is allocated at compile time. Thus, it never has to be deallocated.

There are different sections in a c++ binary. A few examples are text (where the code is stored), the stack, and the heap. There's also a section of read-only static memory. I believe that is where the strings would be stored.

Since the string is not on the heap, it does not need to be freed.

matzahboy
  • 3,004
  • 20
  • 25
  • *"The memory for bar is allocated **at compile time**"*. Well not exactly true! – Nawaz Jul 18 '12 at 08:14
  • There's no such thing as a "C++ binary". And the language standard says nothing about how (or whether) a program is to be compiled into machine code. – Kerrek SB Jul 18 '12 at 08:16
  • Depends on how you interpret the word allocate. The space for it is allocated inside the actual binary, but the word "allocate" does usually refer to runtime heap allocation. – matzahboy Jul 18 '12 at 08:17