Home > other >  Is this an example of stack overflow in c ?
Is this an example of stack overflow in c ?

Time:07-21

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;
}

CodePudding user response:

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, e.g. an array of 1,000,000 ints 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 (e.g. 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. E.g. 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.

CodePudding user response:

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!

  • Related