Interesting C++ ambiguity on Arduino

So, I am creating a Myo/ Arduino based URC and had an interesting c++ encounter.

Less talk, getting straight to code (have less time, gotta get back to work!!). Using pastebin as this is not a self hosted blog and WP won’t let me install the code snippet plugin.

What fails to work is :

http://pastebin.com/rKMqpYgB

That is, when I return the address of a variable (i.e &code) from a function that returns a pointer. I get a junk address.

For the record output was

code value from inside : A90
Oustide file : C002101

However if I return a pointer type variable from a function that returns a pointer type variable, everything is good

What works is this :

http://pastebin.com/YXzf91PJ

 

The output was :

code value from inside : A90
Oustide file : A90

 

So apparently, when using  something like

Code temp_code = Code();

Code* var = &temp_code;

in Visual Micro for Arduino (Atmega 328) programming, the execution environment faces some sorta ambiguity.

Will analyse this later. Currently, hack mode is on \m/

 

 

Advertisements

One comment

  1. siddhu · April 11

    In the failing version of the code, an object has been declared inside a function. This will allocate the memory for the object on the stack, which may be overwritten by another functions’ local variables after the current function returns.

    In the working version, though, this object was saved on heap, which is not overwritten in the manner the stack gets overwritten.

    This is what GCC typically does in _cdecl ABI on x86 systems, avr-gcc might be showing similar behavior in AVR architecture.

    \m/

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s