"Ying Yang" <Yi******@hotmail.com> wrote in message
news:3f********@news.iprimus.com.au...
Hi,
Consider this:
char* ptr = "a string";
Is ptr a pointer to a dynamically created object for which i must use the delete operator to deallocate memory? I'm sure the "a string" part creates an array of characters, and returns a pointer to the first element.
Regards
wert
ptr is definitely NOT a dynamically created object, nor is "a string".
If you attempt to delete ptr, either a run time error will result, or the
memory manager's free list will be messed up.
Memory for literal strings and other 'static' objects is allocated when
the program is loaded, and is not in the realm of dynamically allocated
memory.
I gather that the compiler creates an array of characters for the string
literal on the stack, and thus there is no need to use the delete
operator.
Regards BN
A simplified model (which may not be correct for all compilers) is as
follows. Please note that this is based on my experience writing assembly
language in the early 90's for MS-DOS, and other environments may take
different approaches.
1) static memory: for literal strings, global variables, etc.
2) the stack, storage for function parameters and variables local to
functions, and the address to which the function returns. When a function
is called, the stack pointer (a memory address) is modified so that the
local variables are allocated. At the time I was working with software, one
had to be careful not to overflow the stack into the...
3) The heap: remaining unused memory allocated dynamically, say by malloc()
or new()
Thus, memory might look like this:
STATIC literals, etc.
....
STACK growing down
....
....
....
HEAP growing up.
Thus, in your example, if ptr was declared in a function, a small bit of
stack space enough to store a memory address is associated with 'ptr', the
address contained in 'ptr' refers to an area in the static area where the
literal string is stored.
Where you to define an array of characters, or a std::string, as a local
variable, and assign the literal text to that variable, then the values
contained in the static area would be copied to the appropriate location in
the stack.