简体   繁体   中英

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. 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:

  1. A large object is created on the stack, eg an array of 1,000,000 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.
  2. Too many levels of function calls occur (eg infinite recursion). Each time you call a function an amount of stack memory is used to store the variables of that function along with parameters, return addresses etc. Depending on the amount of memory used by each function, the number of nested function calls you can do without causing a stack overflow will vary. Eg if you create large arrays on the stack you'll be able to do far fewer levels of recursion than if each function just has a few integer variables.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM