String memory management

Dec 20, 2010 at 1:57am
I'm writing some code where it's very important that I leak no memory.

I've had a bit of a look around, and everything I'm reading is pointing out pairing alloc()/free() and new/delete.

Assume variables are being declared locally.

1.

char * foo = new char[100];
vs
char foo[100];

My understanding is the first will only be destroyed upon a call to delete [] and the second will be destroyed when the function returns?

2. What about with static strings such as:

char * foo = "bar";

I assume that foo and "bar" are destroyed on return?

3. What about static strings when passed as parameters?

FILE * foo = fopen("bar", "rb");

And as with #2, "bar" and "rb" will be destroyed on function return?

This may seem rudimentary or ridiculous, but I've never seen it written anywhere (or readily find information on it).

Thanks.
Dec 20, 2010 at 2:36am
1. Yes.
2. foo will be destroyed. "bar" is a string literal, however, and doesn't actually take any memory up itself.
3. Same as above.
Dec 20, 2010 at 3:09am
2. Well it has to sit somewhere, according to what I can find string literals are put into read only memory which means that it's valid for the life of the application?
Dec 20, 2010 at 4:10am
When you do const char* foo = "bar"; it is basically the same as:
const char foo[4] = {'b', 'a', 'r', '\0'};

Thus it simply allocates enough space for "bar" on the stack and points foo to the start, basically the same as 1.
Dec 20, 2010 at 9:16am
String literals are not allocated from the stack - they are allocated from the read-only data section of the program.

1
2
const char* foo = "bar";
foo[2] = 'z';  // <--- segmentation fault 


If they were allocated from the stack, I wouldn't get SEGV here.
Last edited on Dec 20, 2010 at 9:16am
Dec 20, 2010 at 9:42am
closed account (z05DSL3A)
...string literals are put into read only memory which means that it's valid for the life of the application?

Yes, Sting literals have static storage duration.. The storage of them lasts the duration of the program.
Dec 20, 2010 at 9:49am
Okay, that answers it all pretty neatly.

Thanks guys =].
Topic archived. No new replies allowed.