int* pi;
{
int ar[1000000];
int a =3,b=4;
ar[3]=a*b
pi=ar;
}//ar is destroyed
int ar2[]={5,6,7,8,9};
char* f="zcxzsdaaaaaaaaa";
std::cout<<pi[3]<<std::endl;// prints 12
I have 2 questions:
-
I heard that the stack contains only pointers to data. And if so where is the data stored? For example
char* a="bbbb";a – placed on stack, “bbbb” – somewhere else. Where? -
Doesn’t the above code working correctly mean a memory leak of 1000000 bytes? Variable
aris destroyed but the data that it pointed to still exists. And we can’t use delete here sincearis not dynamically allocated.
You heard wrong. The stack contains the actual data. However, if that data is a pointer then that is what is stored.
Yes,
a(the pointer) is stored on the stack. The actual string"bbbb"is stored in a fixed part of the executable.No, there is a difference between arrays and pointers to arrays.
ar(the whole 1000000 bytes) will be stored on the stack. This is different fromchar const* ar = "... 1000000 chars ...";. Asaris on the stack, it will be “freed” automatically.The problem in your code is that
piis pointing to something on the stack which is no longer there. It may well be there when you run the code because “freeing” data on the stack doesn’t do anything to the data in non-debug builds. It’s not a memory leak, you just have an invalid pointer.Final note: Although essentially all modern computer architectures make use of a call stack, the C++ standard makes no mention of it. Note that people will often say that a variable is “on the stack”, but it may actually just live in a register. For example, if you compiled your code, the variable
piprobably wouldn’t ever touch the stack, it would likely just stay in a register for the duration of the function because going to the stack is relatively expensive (compared to registers).