Learning pointers for the first time. So ptr is being assigned n, n1 and finally n2 but n and n1 were never deleted. Hope that makes sense.
#include <iostream>
using namespace std;
int main() {
int n = 5;
int n1 = 7;
int n2 = 8;
int *ptr;
ptr = &n;
ptr = &n1;
ptr = &n2;
cout << ptr << endl;
cout << *ptr << endl;
return 0;
}
The stack is generally a (relatively) small, fixed sized, area of memory allocated to each thread in your application. The stack memory used by a function is automatically released at the end of that function.
A stack overflow is when your program runs out of stack memory. This generally occurs for two reasons:
int
s might use up 4mb of stack memory but on Windows the default stack size is usually 1mb so your program would encounter a stack overflow when the array is created. Neither scenario is occurring in your code, you're creating 4 variables on the stack and assigning values to them. The behaviour is well defined and the memory will be automatically released at the end of main
.
OKAY. Firstly, you did not assign the pointer ptr
to &n
, &n1
and &n2
. You were simply overriding the assignments so at the end of the code, ptr
was only assigned to &n2
.
Secondly, MEMORY OVERFLOW occurs when there is a memory leak and this happens when you use new
keyword to allocate memory and do not use delete
to deallocate it.
#include<iostream>
using namespace std;
int main()
{
int* pointer;
pointer=new int;
*pointer=24;
cout<<*pointer;
delete pointer;
return 0;
}
The above code is the proper way of allocating and deallocating memory. Omitting the delete pointer;
in this case would be an example of a memory overflow.
However, stack overflow is a different thing and it does not apply here.
I hope this helps!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.