I was trying to call a function that was allocated in the heap. After some failed attempts I tried the code in this website:
http://social.msdn.microsoft.com/forums/en-US/vcgeneral/thread/85d5da8c-edef-44b0-b42e-deb5f3eb2524
The code works flawlessly. It compiles, run, give the correct/expected result and finishes with no problem.
However if I try adding something like std::cout << “Hello World!” << std::endl in the function, copy it to the heap and then execute the heap function it just doesn’t work. If there’s a cout there it don’t work, without the cout it works.
I would like to know why this happens, and how can I solve this problem. Realize that I am doing this with the only purpose of learning, I have no interest in applying this to the practical usage.
If I the heap function calls a function that uses std::cout to print data, that code doesn’t work either.
Your problem lies with the fact that when you add the
coutcode to the function you essentially add some function calls. Microsoft C/C++ compiler uses some basic stack frame checking for detection of problems in runtime. Those checks are performed by calling the__RTC_CheckEspfunction after each function call. The call to__RTC_CheckEspuses the E8 opcode which means relative addressing. When the sample function is moved to the heap, the call to__RTC_CheckEspbecomes erroneous since it jumps to the wrong location.Disable the runtime stack frame checking (in Visual Studio 2010): Project options -> Configuration Properties -> C/C++ -> Code Generation -> Basic Runtime Checks -> set it to Uninitialized Variables
Recompile. Run. Enjoy!