Posts Tagged ‘ Development ’

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.

Advertisements

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.

Want to learn C#?

I’ve been wanting to learn C# for a while so I finally started learning it a few weeks ago. I lightly touched C# back in the fall of 2009. We had a quick crash course trying to get a XNA game working thinking that was the best way to make a game in two weeks. That was a very terrible learning situation and I haven’t thought much about C# since then. Once I decided to take a shot at it again, I was definitely a lot wiser than I was 1.5 years ago. Now that I’ve got some good C++ programming, MFC UI development, and Visual Studio usage skills down, jumping into C# was not as hard as it was when I first came across it. Actually, working with C# in Visual Studio is so much easier than C++ and MFC that I feel like I’ve been converted to a new religion. Seriously, how did I live without this all my programming life?! String conversions, getting file paths/names/extensions, and capturing events are just one call away instead of some hackjob conversion and string parsing! C++ and MFC is like driving a Volvo 240: solid, reliable, and old, but hard to work on and possibly relies on hackjob repairs to make things work. C# with .NET is like a brand new Volvo S60: new, easy to use (from the driver’s seat), and safe with all the electro-nannies, but it’s a lot more complicated under the hood, but you’re not likely to go that deep anyways. I followed the tutorial at Home and Learn and got a nice primer on C#. The tutorials are very easy to read and understand so I recommend checking it out if you’re a beginner. It’s nice that Microsoft offers Visual Studio Express for free to play around with also. Get Visual Studio Express and start making some programs!

Is there an Android API for Google Maps 5.0?

I’ve been looking for this for some personal projects today. After a few hours of research and testing on 3/29/2011, my definitive answer is no.

There remains an unanswered comment on the official blog post about it here from December, and when using the latest 2.3.3 Google APIs in the SDK, I still receive tile based maps. I have also found numerous unanswered questions from stackoverflow and other QA sites to back up my statement that it is currently unavailable.

I will update this post when the Maps 5.0 API becomes updated, or if anyone hears otherwise before I do, please comment!

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

Word Clock gets its own page

Minor update, I’ve created a page for Word Clock. I’ve also turned Word Clock into a Chrome extension (which has a nice icon in the toolbar and a pop-up instead of a full-screen tab). Check it out at the new Word Clock page!

Word Clock
http://wordclock.phamous-apps.com/