Michael wrote:
Default User wrote:
>>using namespace std;
int main()
{
char* ptr;
ptr="abc";
cout<<ptr;
return 0;
}
There is no dynamic memory allocation above.
>>Won't the memory be cleared after executing the above code?
What memory? No memory was allocated.
I am confused.
when ptr="abc" no memory was assinged to the point?
all the memory assignment & delete have to deal with
new or delete ?
Please help me out.
Thanks,
Michael
C++ defines three "storage durations", static, automatic, and dynamic.
Objects with static storage duration exist for the duration of the
program. String literals, such a "abc" in your example, have static
storage duration.
Objects with automatic storage duration exist until the end of the block
in which they are created. The pointer ptr in your example has
automatic storage duration.
Objects with dynamic storage duration exist between the time they are
created with new, and the time they are destroyed with delete. You do
not have any of those in your example.
Though the standard does not place any requirements on how any of that
is implemented, a typical implementation is that objects with static
storage duration are created as part of the binary image, objects with
automatic storage duration are created on some type of system stack, and
objects with dynamic storage duration exist in some part of memory that
is managed by your libraries or OS and sometimes referred to as "the heap".
So, to answer your question, the line:
ptr = "abc";
does cause the variable ptr (which has automatic storage duration) to
contain the address of the string literal "abc" (which has static
storage duration), but at no time is there any dynamic memory allocation
occurring.
--
Alan Johnson