Jan Turoň
Jan Turoň

Reputation: 32912

String as function argument: how to work with the memory?

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.)

Upvotes: 1

Views: 238

Answers (3)

Chefire
Chefire

Reputation: 139

"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.

Upvotes: 2

James Kanze
James Kanze

Reputation: 154027

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

Upvotes: 4

matzahboy
matzahboy

Reputation: 3024

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.

Upvotes: 1

Related Questions