Archive for the ‘ Concept ’ Category

Learn from my fail: check your pointers

I spent quite some time tracking down an issue I was having with my C++ project. Here is a snippet of the code:

class foo
{
private:
    bool* myArray;

public:
    foo()
    {
        myArray = new bool[5];

        for(int i=0; i<5; i++)
        {
            myArray = false;
        }
    }

    void init()
    {
        myArray[0] = true;
    }
};

Every time I ran it, it would throw a memory access violation. I was very puzzled by this since it was just a standard boolean array holding true or false. It wasn’t anything very advanced. I used the Visual Studio debugger to poke around. It goes through the constructor fine and then when it goes into the init() function myArray would become a null pointer. The debugger would report that myArray has a memory address of 0x00000000.

I was very confused because how could the pointer be initialized properly in the constructor, but not be initialized when I step into another function in the same object? I chased it all afternoon and decided to give up and walk away. The next morning, I looked at the code again. Then it hit me: the problem and solution was staring at me in the face.

In the for loop in the constructor I have this code:

myArray = false;

I had forgotten to put in the array subscript! If myArray was a true null pointer, it would have just said it was uninitialized or “nullptr” with a stop icon instead of a zero memory location. What was happening was that the pointer was being set to false, which is zero. That is why the debugger showed that the memory location was 0x00000000. So when I access the pointer to assign a value, I am accessing memory that is already reserved or in-use so it throws a memory access violation. The code is “valid” which is why it doesn’t show any errors during compilation, but it doesn’t produce the desired results at runtime.

With the correct code:

myArray[i] = false;

Everything works fine and I was able to continue my project! After working with C# for a while, it’s an eye opener how much the .Net garbage collector and managed heap does for the programmer.

Enumeration and arrays

Recently, I discovered the usefulness of the enum type in C++. I can’t believe how long I’ve gone without using an enum because I didn’t know why I should use it over a #define. The two main reasons to use enums over #define is 1) sequential self-numbering and 2) enums allow the value to be visible to the debugger. This post is about the first reason.

Let’s say we want a list of variables, and the variables need to be assigned a unique number for processing, but we don’t care what number is assigned to it. Enumeration to the rescue! Define an enum with a list of variables and it will assign each variable an integer value starting from zero. For example:

enum
{
    alpha,
    beta,
    delta,
    gamma
};

// The values stored in the enum variables are:
// alpha == 0
// beta == 1
// delta == 2
// gamma == 3

Now you can add another variable to the the list in any position (because remember we don’t care what number is assigned to it, it just has to be a unique number) and you won’t have to renumber the other values. It just does it automatically!

enum
{
    alpha,
    beta,
    omega, //<---------
    delta,
    gamma
};

// The values stored in the enum variables are:
// alpha == 0
// beta == 1
// omega == 2
// delta == 3
// gamma == 4

You’re probably thinking: “Great, it self-numbers. What’s the point?” Well the point is that you can use this as array indices and declarations. Assume you have some boolean option settings for your program with the following options: isFullScreen, isWidescreen, isMoving.

Let’s start out making a new file called “options.h” with the following code:

namespace options
{
    enum
    {
        isFullScreen,
        isWidescreen,
        isMoving,
        size
    };
}

I put the enum inside a namespace so that I can use the enum in multiple places without creating an instance of an object. The namespace also allows Visual Studio to list all the enum variables in the autocomplete dialog when using the scope operator ("::"). All I need to do is add #include "options.h" to the top of the header files where I want to use this enum. The last variable size is always going to be the size of the array. Now, remember an enum variable is a const integer value which is why we can use it as an array index value. To use this enum in a class I would use the following code snippet:

// include the namespace file
#include "options.h"

// declares the array, but does not initialize the elements
bool myOptions[options::size];

// then I can initialize the values like so:
myOptions[options::isFullScreen] = false;
myOptions[options::isWidescreen] = false;
myOptions[options::isMoving] = false;

...

// usage example
if(myOptions[options::isFullScreen])
{
    // do something
}

That’s fine and dandy, but if we add another option, we would have to add another line to set that option to false on initialization. We’re lazy and are willing to write more code now to prevent having to write more code in the future so let’s add a reset function to the options namespace.

namespace options
{
    enum
    {
        isFullScreen,
        isWidescreen,
        isMoving,
        size
    };

    static void Reset(bool myArray[options::size], bool value);
}

// the following lines of code are in the same file as the namespace
/**
@brief Resets all the options to a specific value
@param myArray  The array of options using the namespace's enum
@param value    The value to assign to all the options
*/
void options::Reset(bool myArray[options::size], bool value)
{
    for(int i=0; i<options::size; i++)
    {
        myArray[i] = value;
    }
}

I put a value as a parameter because I want the flexibility to set all the options to true or false. The static keyword allows us to use the function without declaring an object so we just reference the function like so in the class:

// declares the array, but does not initialize the elements
bool myOptions[options::size];

// resets all the options
options::Reset(myOptions, false);

...

// usage example
if(myOptions[options::isFullScreen])
{
    // do something
}

Now let’s add another option to the enum to detect if a file is loaded:

namespace options
{
    enum
    {
        isLoaded, //<-----------
        isFullScreen,
        isWidescreen,
        isMoving,
        size
    };

    static void Reset(bool myArray[options::size], bool value);
}

The beauty of this is I can add this function without having to renumber or edit the existing code! I just add the new option where I need to use it.

// still works correctly
if(myOptions[options::isFullScreen])
{
    // do something
}

// do this for the new option
if(myOptions[options::isLoaded])
{
    // do something
}

This is not the only example for using enums with arrays. There are so many possibilities such as having an array of strings and looping through it to read the values. Learning how to use enums for arrays changed my life. It has made me more productive and made maintenance so much easier. It’s such an elegant, cheap, and easy way to improve the code tenfold.

If Linux was a car

Really? But your car still runs with Windows

Linux enthusiasts are scary

Shameless cross-post from my car blog: http://yudrivebad.wordpress.com/

(Recursion!!!!)

If Linux was a car, you’d have to build it from scratch just to go to the store to buy some milk. You’d start by compiling an engine and put it on a chassis. That’s fine and dandy and it’ll get you where you need to guy, but it sure is a pain in the ass to turn with a socket wrench on the rack and pinion. So let’s put in a steering column and steering wheel.

It’s not very comfortable so let’s add some seats. Now you realize there are different flavors of seats. Bench, bucket, velour, cloth, leather, etc. Bench sounds nice which is great for cuddling with a significant other! Oh wait, you use Linux. Scratch that, let’s go with buckets for the sportier feel.

Great, but it’s not that great looking. It needs a body. Those damn Apple cars look so sleek and sexy with their glossy exterior, but we all know you can’t modify them. Fk the sheeple and their pretty cars. Those Windows cars actually look pretty good now unlike a few years ago when the Fisher Price Cozy Coup called them out on plagiarism. What can I do with the Linux car? Well, there’s not much to choose from out of the box. Fkr looks cartoony. Meh, fk it, let’s roll.

It drives just as well as the Apple car because they’re almost identical under the hood. You’re feeling pretty smug because you built your own car for free. Well, let’s keep adding mods. You want lib-vtec-honda, but it won’t work in your car. You hack it to work instead. You’re somewhat successful, but you needed another obscure library to get it to work: lib-jdm-bolts. Ok, it works fine, but not perfect.

Oh no, the radio stopped working! Ok, don’t panic, just use another antenna. Crap, it’s not compatible with Linux and you just paid out the butt for it. To the Googles! So many people have the same issue, but with different hardware. WTF?! Grrrr! Ok, this guy says to download ndis-radio-wifi-2.6.1 and compile it for my specific car. Ok. Fk! I need another obscure library: lib-am-fm-cassette. Don’t I already have that?! Jebus H. Chrysler this is retarded.

Wheee, got the radio working. Let’s roll. Going to Taco Bell for some chalupas and Baja Blast. Oh muffin fudger, it doesn’t have a fkn cupholder. Google it. Cupholders aren’t available to Linux due to it being proprietary technology developed by Adobe?! GD it to hell! You end up burning the car and buying a Windows car.

How to shoot yourself in the foot in any programming language

Searching through the documents on my hard drive this weekend I came across a document containing the joke of how to shoot yourself in the foot in any programming language. Well, not literally, but it does relate how the different languages behave by using the analogy of shooting one’s self in the foot. I forgot where I found this so if someone knows, post the link in the comments!

* * *

How to Shoot Yourself in the Foot in Any Programming Language

The proliferation of modern programming languages (all of which seem to have stolen countless features from one another) sometimes makes it difficult to remember what language you’re currently using. This guide is offered as a public service to help programmers who find themselves in such dilemmas.

C
You shoot yourself in the foot.

C++
You accidentally create a dozen clones of yourself and shoot them all in the foot. Providing emergency medical assistance is impossible since you can’t tell which are bitwise copies and which are just pointing at others and saying, “That’s me, over there.”

JAVA
After importing java.awt.right.foot.* and java.awt.gun.right.hand.*, and writing the classes and methods of those classes needed, you’ve forgotten what the hell you’re doing.

Ruby
Your foot is ready to be shot in roughly five minutes, but you just can’t find anywhere to shoot it.

PHP
You shoot yourself in the foot with a gun made with pieces from 300 other guns.

ASP.NET
Find a gun, it falls apart. Put it back together, it falls apart again. You try using the .GUN Framework, it falls apart. You stab yourself in the foot instead.

SQL
SELECT @ammo:=bullet FROM gun WHERE trigger = ‘PULLED’;
INSERT INTO leg (foot) VALUES (@ammo);

Perl
You shoot yourself in the foot, but nobody can understand how you did it. Six months later, neither can you.

Javascript
You’ve perfected a robust, rich user experience for shooting yourself in the foot. You then find that bullets are disabled on your gun.

CSS
You shoot your right foot with one hand, then switch hands to shoot your left foot but you realize that the gun has turned into a banana.

FORTRAN
You shoot yourself in each toe, iteratively, until you run out of toes, then you read in the next foot and repeat. If you run out of bullets, you continue anyway because you have no exception-handling ability.

Modula2
After realizing that you can’t actually accomplish anything in this language, you shoot yourself in the head.

COBOL
Using a COLT 45 HANDGUN, AIM gun at LEG.FOOT, THEN place ARM.HAND.FINGER. on HANDGUN.TRIGGER and SQUEEZE. THEN return HANDGUN to HOLSTER. CHECK whether shoelace needs to be retied.

LISP
You shoot yourself in the appendage which holds the gun with which
you shoot yourself in the appendage which holds the gun with which
you shoot yourself in the appendage which holds the gun with which
you shoot yourself in the appendage which holds the gun with which
you shoot yourself in the appendage which holds ….

BASIC
Shoot yourself in the foot with a water pistol. On big systems, continue until entire lower body is waterlogged.

FORTH
Foot in yourself shoot.

APL
You shoot yourself in the foot, then spend all day figuring out how to do it in fewer characters.

Pascal
The compiler won’t let you shoot yourself in the foot.

SNOBOL
If you succeed, shoot yourself in the left foot.
If you fail, shoot yourself in the right foot.

Concurrent Euclid
You shoot yourself in somebody else’s foot.

HyperTalk
Put the first bullet of the gun into the foot of the left leg of you.
Answer the result.

Motif
You spend days writing a UIL description of your foot, the trajectory, the bullet, and the intricate scrollwork on the ivory handles of the gun. When you finally get around to pulling the trigger, the gun jams.

Unix
% ls
foot.c foot.h foot.o toe.c toe.o
% rm * .o
rm: .o: No such file or directory
% ls
%

Paradox
Not only can you shoot yourself in the foot, your users can too.

Revelation
You’ll be able to shoot yourself in the foot just as soon as you figure out what all these bullets are for.

Visual Basic
You’ll shoot yourself in the foot, but you’ll have so much fun doing it that you won’t care.

Prolog
You tell your program you want to be shot in the foot. The program figures out how to do it, but the syntax doesn’t allow it to explain.

Ada
After correctly packaging your foot, you attempt to concurrently load the gun, pull the trigger, scream and shoot yourself in the foot. When you try, however, you discover that your foot is of the wrong type.

Assembly
You try to shoot yourself in the foot only to discover you must first reinvent the gun, the bullet, and your foot. After that’s done, you pull the trigger, the gun beeps several times, then crashes.

370 JCL
You send your foot down to MIS with a 4000-page document explaining how you want it to be shot. Three years later, your foot comes back deep-fried.

Python
You try to shoot yourself in the foot but you just keep hitting the whitespace between your toes.

Dividing an array

Even if you don’t care about the practical applications of it in modern programming, it offers a look back when programming was more of a pain in the ass because shit needed to be set up properly as well as having a good algorithm. Actually it is still relevant in deeper technical programming that is closer to the hardware level. Probably not so much for app developers.

So let’s say you have an array using 16-bit integers. So you would have something like this:

unsigned short *myArray = new unsigned short[1024];

So you fill it up with data and all is good right? Well now your next requirement is that you want to divide each element into two parts, the lower byte and upper byte because the upper byte indicates the flashing pattern of the red LED and the lower byte indicates the flashing pattern of the green LED. Well FML, right? No!

We make a new byte pointer (a char in this case) and make it point to the typecasted main array:

unsigned char* birchPointer;
birchPointer = (unsigned char*) myArray;

Now because a char is a byte in size, when you advance the index it will point to the next 8-bit position. So let’s say myArray contains the following information:

myArray[0] = 0xBEEF;
myArray[1] = 0xCAFE;
myArray[2] = 0xBABE;

Now if you use the char pointer to access myArray, you’ll get the following information (providing your system is big endian):

birchPointer[0] = 0xBE;
birchPointer[1] = 0xEF;
birchPointer[2] = 0xCA;
birchPointer[3] = 0xFE;
birchPointer[4] = 0xBA;
birchPointer[5] = 0xBE;

If you’re using a machine that’s little endian (which most PCs are), then the byte values will be swapped like so (due to little endian storing the lower byte first in the memory sequence):

birchPointer[0] = 0xEF;
birchPointer[1] = 0xBE;
birchPointer[2] = 0xFE;
birchPointer[3] = 0xCA;
birchPointer[4] = 0xBE;
birchPointer[5] = 0xBA;

So there you have it: splitting a 16-bit array into an 8-bit array and learning something about how endians affect it.

Read more:
Size of C++ Datatypes
Big endian vs. little endian

Stop compiling, Mister Falcon!

Rage face!

Muffin fudger!


When I’m working in Visual Studio I have stored in my muscle memory a swift stroke of F7. F7 is the key that saves all files and compiles/builds my program without running it. I do this to check for compilation errors in the program (yes I’m a terrible programmer, STFU). Normally it doesn’t take too long, but I’ve only been working with small to medium sized projects. Recently I have been working on a much larger project and compilation on this program takes DAYS!! Ok, not really days, but more like two minutes, which takes days in computer time. I would hit F7 out of habit and then rage because it required a special compilation step instead of the automatic way to compile. This pissed me off to no end. I summoned the almighty Google and discovered that CTRL+Pause(Break) will stop compiling in Visual Studio. It’s so simple, a caveman could do it! That’s one less rage face I’ll be making during my days.

Learn how to code!

LifeHacker recently did a series on the basics of programming. In their articles, they are using JavaScript which is very easy to use and you don’t need to download any SDK or compiler. Just open up your favorite text editor and do your code, then save and view the results in your favorite web browser. Here are the links in case you missed it:

Part 1: Variables and Datatypes
Part 2: Working with Variables
Part 3: Arrays and Logic Statements
Part 4: Understanding Functions and Making a Guessing Game
Part 5: Learn to Code Epilogue: Best Practices and Additional Resources