I want to know the difference between dynamic memory, stack memory and static memory in C++.
Here is some code as an example:
#include<iostream>
using namespace std;
char *GetMemory(void)
{
char p[]="hello world";
char *q="hello world";
return q;
}
int main(void)
{
return 0;
}
Why is p in the stack memory, but the q in dynamic memory?
pandqare both variables.pis of type “array of 12char” andqis of type “pointer tochar“. Bothpandqhave automatic storage duration. That is, they are allocated on the stack.qis a pointer and it is initialized to point to the initial character of the string"hello world". This string is a string literal, and all string literals have static storage duration.pis an array, so when you initializepwith a string literal, it causespto declare an array of characters, and when it is initialized, the contents of the string literal are copied into the array. So, whenGetMemory()is called, space is allocated on the stack for the arrayp, and the contents of the string literal"hello world"are copied into that array.No dynamic allocation is performed by your code.
Note that because
qis a pointer to an array of characters that have static storage duration, it is safe to returnqfrom the function: the array to which it points will exist for the entire duration of the program. It would not be safe to returnp, however, becausepceases to exist when the function returns.Note also that the type of
"hello world"ischar const[12]. There is an unsafe implicit conversion in C++ that allows a string literal to be converted to achar*pointing to the initial character of the string literal. This is unsafe because it silently drops the const-qualification. You should always useconst char*when handling string literals, because the characters are not modifiable. (In the latest revision of the C++ language, C++11, this unsafe conversion has been removed.)