Dec 20, 2010 at 1:57am Dec 20, 2010 at 1:57am UTC
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 Dec 20, 2010 at 2:36am UTC
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 Dec 20, 2010 at 3:09am UTC
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 Dec 20, 2010 at 4:10am UTC
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 Dec 20, 2010 at 9:16am UTC
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:16am UTC
Dec 20, 2010 at 9:49am Dec 20, 2010 at 9:49am UTC
Okay, that answers it all pretty neatly.
Thanks guys =].