Friday, January 29, 2016

Avoiding Unsafe Code in Vala

CSharp uses the 'unsafe' keyword to mark sections of code that ignore type safety. Vala doesn't have this,  but if it did, if would apply to variable length argument lists.

What's wrong with variable length arguments? The tutorial shows a great use case:

actor.animate (AnimationMode.EASE_OUT_BOUNCE, 3000, x: 100.0, y: 200.0, rotation_angle_z: 500.0, opacity: 0);

Coming from a scripting world, this looks like a friendly idiom. In fact, this example has a bug that causes unpredictable results. See that last parameter 'opacity: 0'? That '0' should be a '0.0', because the receiving method:

double val = l.arg();

is requesting a double. Now the stack is out of alignment. If you are lucky, your program will crash with a segmentation fault. Lucky? Yes, because any other result is unpredictable. In my case, the values of all 4 variables became changed to 0, and the program continued running. But the other part of the example seemed to work correctly:

actor.animate (AnimationMode.EASE_OUT_BOUNCE, 3000, "x", 100.0, "y", 200.0, "rotation-angle-z", 500.0, "opacity", 0);

This was giving me the correct results. So I assumed that the problem was with the alternate syntax, which uses a colon. Then I swapped the two, expecting the error to move with it. But it didn't. Now the alternate syntax was working. That should have been my first clue that there was a memory corruption. Instead, seeing that I was using an older version of Vala libraries, I upgraded to the newest. And the problem went away. I thought I'd fixed it. But it wasn't fixed.

I was wrong. Later the next day, it started doing it again. Sorry stackoverflow, you were right. It's been a long time since I've coded using c.

That's when I noticed the '0'. I changed that to '0.0' and it started working. This is how a memory bug presents in C - it wants you to pull your hair out. My advice - don't use variable length argument lists. This 'wolf in sheeps clothing' masquerades as a friendly looking idiom but it's not.

No comments:

Post a Comment