-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathScopeFaultScenario.cpp
More file actions
58 lines (44 loc) · 1.45 KB
/
ScopeFaultScenario.cpp
File metadata and controls
58 lines (44 loc) · 1.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
* \file ScopeFaultScenario.cpp
* \brief
*
* \review
*/
#include <StdStream/StdStream.h>
#include <StdTest/StdTest.h>
#include <Stl.h>
//--------------------------------------------------------------------------------------------------
std::function<void ()>
getCallBack()
{
int counter {10};
// Capturing Local variables by Reference
auto func = [&counter] () mutable
{
std::cout << "Inside Lambda :: " << STD_TRACE_VAR(counter) << std::endl; // TODO: ????
// Change the counter
// Change will affect the outer variable because counter variable is
// captured by Reference in Lambda function
counter = 20;
std::cout << "Inside Lambda :: After changing :: " << STD_TRACE_VAR(counter) << std::endl;
};
return func;
}
//--------------------------------------------------------------------------------------------------
int main(int, char **)
{
auto func = getCallBack();
// Call the Lambda function
func();
// Lambda function will access and modify the variable that has been captured it by reference
// But that variable was actually a local variable on stack which was removed from stack
// when getCallbacK() returned
// So, lambda function will basically corrupt the stack
return EXIT_SUCCESS;
}
//--------------------------------------------------------------------------------------------------
#if OUTPUT
Inside Lambda :: counter: 21881
Inside Lambda :: After changing :: counter: 20
Segmentation fault (core dumped)
#endif