Victor
Victor

Reputation: 1703

Why this function called in the heap can't call cout?

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.

Upvotes: 0

Views: 417

Answers (3)

Hristo Iliev
Hristo Iliev

Reputation: 74365

Your problem lies with the fact that when you add the cout code 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_CheckEsp function after each function call. The call to __RTC_CheckEsp uses the E8 opcode which means relative addressing. When the sample function is moved to the heap, the call to __RTC_CheckEsp becomes 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!

Upvotes: 1

David Heffernan
David Heffernan

Reputation: 612804

In the article that you refer to, it states:

Only use local variable, don't use global variable, static variable, and constant string variable.

But std::cout is a global. And I think that string literal would probably be classed as as "constant string variable" although the articles terminology is somewhat imprecise.

As others state the behavior of this code is undefined so exactly what happens is implementation specific. Different compilers may behave differently.

Upvotes: 3

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

You are relying on undefined behaviour here, and expecting it to do something sane.

If you want to know what's going "wrong" on your particular platform, I suggest using the debugger to step through the machine code.

Upvotes: 2

Related Questions