String memory management

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.
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.
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?
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.
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
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.
Okay, that answers it all pretty neatly.

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