Post by wwjHi ,all
I want to know the difference between char a[6] and char *p=new
char[6] and the difference between the heap and the stack ,and if the
char a[6] is corresponding to the stack in MEMORY,and char *p=new
char[6] is corresponding to the heap of MEMORY.
Give me some hint.
THANK YOU.
int main()
{
char a[6];
}
a
+---+---+---+---+---+---+
| | | | | | |
+---+---+---+---+---+---+
//////////////////////////////////////////////////
int main()
{
char *p = new char[6];
}
p
+------+ +---+---+---+---+---+---+
| o----------------->| | | | | | |
+------+ +---+---+---+---+---+---+
In the first example, a is an array which is large enough to store
6 characters.
In the second example, p is a pointer. This pointer points to dynamically
allocated memory, which is large enough to store 6 characters.
As for heap vs. stack. C++ doesn't use the terms heap/stack. C++ uses the
terms automatic storage and dynamic storage (among others). a is allocated
on the automatic storage, meaning: whenever the variable goes out of scope,
the memory for that variable is destroyed.
p is also allocated on the automatic storage, but the memory where p points
to is allocated dynamically. Such memory is released only when a correspondig
delete [] (or delete) is done on the pointer value.
int main()
{
{ // start a new scope
char a[6];
// a
// +---+---+---+---+---+---+
// | | | | | | |
// +---+---+---+---+---+---+
} // end the scope, all variables introduced in that scope
// are destroyed. In this case this means: no variables left
}
/////////////////////////////////////////////////
int main()
{
{ // start a new scope
char *p = new char[6];
// p
// +------+ +---+---+---+---+---+---+
// | o----------------->| | | | | | |
// +------+ +---+---+---+---+---+---+
} // end the scope, all variables introduced in that scope
// are destroyed. In this case this leads to
//
// +---+---+---+---+---+---+
// | | | | | | |
// +---+---+---+---+---+---+
// Note: The pointer p has been destroyed, since it is in automatic
// storage. But not so the memory it has been pointing to. There is no
// longer any pointer pointing to it: Congratulations, you have created
// a memory leak, that memory, although still allocated to your program,
// is inaccessible for your program.
}
Does that answer your questions?
--
Karl Heinz Buchegger
***@gascad.at