title: The scope of local variables captured by a lambda function (C++)
body: <p>I searched everywhere but could not find an answer to my question. I am trying to write an example that shows that capturing a local variable of the enclosing function by reference is dangerous because it may not exist anymore when it is actually referenced. Here's my example: </p>
  
  <pre><code>#include &lt;iostream&gt;
  
  
  std::function&lt;int (int)&gt; test2(int l) {
         int k = 10;
         return [&amp;] (int y) { return ++k + 100; };
  }
  
  
  void test(std::function&lt;int (int)&gt; k) {
          std::cout &lt;&lt; k(100);
  }
  
  int main() {
          test(test2(100));
  
          std::function&lt;int (int)&gt; func = test2(100);
          test(func);
  
          return 0;
  }
  </code></pre>
  
  <p>I tried to reproduce stack corruption from trying to access and modify a local variable that doesn't exist on the stack frame by returning a lambda function from <em>test2</em> that captures a local variable <em>k</em> and modifies it. </p>
  
  <pre><code>std::function&lt;int (int)&gt; func = test2(100);
  test(func);
  </code></pre>
  
  <p>prints out a garbage value which indicates something went wrong as expected. However, </p>
  
  <pre><code>test(test2(100));
  </code></pre>
  
  <p>prints out "111". This is confusing to me as I thought when test2(100) returns a lambda function of type std::function, the stack frame for test2 will be gone, and when test is invoked, it should not be able to access the value of k. I'd appreciate any ideas or keywords I can use to search for answers. </p>