Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory leak on the stack

Is it possible to create memory leak in C++ without heap allocation, through very bad design ?

One example I had in mind, please correct me if it does not do what I think it does:

#include <iostream>
#include <string>

void WhatIsYourName()
{
  std::string name;
  std::cout << "What is your name? ";
  getline (std::cin, name);
  std::cout << "Hello, " << name << "!\n";

  WhatIsYourName();
}

int main()
{
  WhatIsYourName();
}

To me it looks like WhatIsYourName() is initializing a new std::string name on every call, but the function never really goes out of scope so the memory is never released. Is that right ? Or is the compiler smart enough to see that the variable will not be used in the future, so it deletes it without the function going out of scope ?

What kind of other bad design would create a memory leak using only stack allocation ?

like image 753
Jean-Emmanuel Avatar asked Dec 07 '22 20:12

Jean-Emmanuel


1 Answers

You have a recursive call that doesn't stop (there's no exit condition), so a new stack page is created for every function invocation, until of course the program crashes due to stack overflow. The compiler cannot optimize that away.

Regarding your last question, whether is possible to create a memory leak without heap allocation (and without this kind of infinite recursion), I believe it is not, the local variables are automatically released, that's why this type of storage duration is called automatic storage duration.

like image 111
vsoftco Avatar answered Dec 10 '22 11:12

vsoftco