I have learned that
char szA[] = "abc";
uses "abc" to initialize array szA, so it is stored in the stack memory and will be destroyed when function ends.
On the other hand, consider:
char * szB = "abc";
In here "abc" stored in the data memory section like static variables, and szB is just an address of it.
In this point, I was wonder:
If I try
int i = 0;
while(i++ < 1000000)
char * szC = "hello"
will this make 1000000 of "hello" in data section?
To figure this out, I have written test code:
#include <iostream>
using namespace std;
char* testA(char* arr)
{
return arr;
}
char* testB(char* arr)
{
return arr;
}
void main()
{
cout << "testA---------------\n";
cout << int(testA("abc")) << endl;
cout << int(testA("cba")) << endl;
cout << "testB---------------\n";
cout << int(testB("abc")) << endl;
cout << int(testB("cba")) << endl;
cout << "local---------------\n";
char* pChA = "abc";
cout << int(pChA) << endl;
char* pChB = "cba";
cout << int(pChB) << endl;
}
And the result is:
testA---------------
9542604
9542608
testB---------------
9542604
9542608
local---------------
9542604
9542608
So, apparently there is only one space for each string literal in data memory.
But how does the compiler know that the literal string(const char*)
already exists in data memory?