[英]Is this an example of stack overflow in c++?
Learning pointers for the first time.第一次学习指针。 So ptr is being assigned n, n1 and finally n2 but n and n1 were never deleted.
所以 ptr 被分配 n、n1 和最后 n2 但 n 和 n1 从未被删除。 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.int
的数组可能会占用 4mb 的堆栈内存,但在 Windows 上,默认堆栈大小通常为 1mb,因此您的程序在创建数组时会遇到堆栈溢出。 Neither scenario is occurring in your code, you're creating 4 variables on the stack and assigning values to them.这两种情况都不会在您的代码中发生,您正在堆栈上创建 4 个变量并为它们分配值。 The behaviour is well defined and the memory will be automatically released at the end of
main
.行为定义明确,内存将在
main
结束时自动释放。
OKAY.好的。 Firstly, you did not assign the pointer
ptr
to &n
, &n1
and &n2
.首先,您没有将指针
ptr
分配给&n
、 &n1
和&n2
。 You were simply overriding the assignments so at the end of the code, ptr
was only assigned to &n2
.您只是覆盖了分配,因此在代码末尾,
ptr
仅分配给&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.其次,当存在内存泄漏时会发生 MEMORY OVERFLOW,并且当您使用
new
关键字分配内存并且不使用delete
释放它时会发生这种情况。
#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;
省略
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!我希望这有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.