Posts Tagged ‘ programming ’

Do people in other countries program in English?

I was browsing Stack Overflow’s programming section and came across an interesting topic asking if programmers in other countries code in English. This answer from a Canadian is hilarious:

I’m from Canada, but live in the States now.

It took me a while to get used to writing boolean variables with an “Is” prefix, instead of the “Eh” suffix that Canadians use when programming.

For example:

MyObj.IsVisible

MyObj.VisibleEh

I should name my boolean variables that way from now on.

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.

Formatting and Styling Strings (C#)

We’ve discussed different ways to format a string using printf for C++ and string.format for Java/Android and since I’ve been working with C# recently I would add that to the blog as well.

In C#, it’s just like Java/Android: use string.Format(). Instead of dollar signs, you would use curly brackets with the parameter number. What’s nice is that you don’t really need to worry about the type. For example:

int foo = 9000;
string bar = "sparta";

string fubar = string.Format("This is {0}! It is over {1}!", bar, foo);

Would result with:

This is sparta! It is over 9000!"

See how I didn’t need to tell it {0} was a string and {1} was an integer? You can also add the format inside the curly bracket if you wish such as:

{index,length:formatString}

Where index is the index of the value to use; length is the amount of spaces you want this variable to take up; and formatString is a standard or custom string that can be used to do more formatting (such as setting up a date in US or EU format).

As usual, if you’d like to know more about the details, visit MSDN for more reading.

Crypto++ and Linux

This week I’ve re-acquainted myself with Linux at work in order to port an app from Windows to Linux. Besides the aggravation of setting up the OS, IDE, and workflow, I had to use a 3rd party library called Crypto++. Well, it wasn’t obvious to set up or figure out so I’d put this out there in case someone has the same problem.

Basically I was able to include the files, but I got a linker error despite including the files in the project file in Qt. This is the error:

g++ -o encrypter -L/usr/lib -Lcryptopp -lcrypto++ -lQtGui -lQtCore -lpthread
encrypter.o: In function `CryptoPP::AllocatorWithCleanup::allocate(unsigned int, void const*)':
encrypter.cpp:(.text._ZN8CryptoPP20AllocatorWithCleanupIhLb1EE8allocateEjPKv[CryptoPP::AllocatorWithCleanup::allocate(unsigned int, void const*)]+0x2b): undefined reference to `CryptoPP::AlignedAllocate(unsigned int)'
encrypter.cpp:(.text._ZN8CryptoPP20AllocatorWithCleanupIhLb1EE8allocateEjPKv[CryptoPP::AllocatorWithCleanup::allocate(unsigned int, void const*)]+0x38): undefined reference to `CryptoPP::UnalignedAllocate(unsigned int)'
encrypter.o: In function `CryptoPP::AllocatorWithCleanup::deallocate(void*, unsigned int)':
encrypter.cpp:(.text._ZN8CryptoPP20AllocatorWithCleanupIhLb1EE10deallocateEPvj[CryptoPP::AllocatorWithCleanup::deallocate(void*, unsigned int)]+0x25): undefined reference to `CryptoPP::AlignedDeallocate(void*)'
encrypter.cpp:(.text._ZN8CryptoPP20AllocatorWithCleanupIhLb1EE10deallocateEPvj[CryptoPP::AllocatorWithCleanup::deallocate(void*, unsigned int)]+0x32): undefined reference to `CryptoPP::UnalignedDeallocate(void*)'
collect2: ld returned 1 exit status
make: Leaving directory `/home/alex/projects/encrypter'
make: *** [encrypter] Error 1
Exited with code 2.
Error while building project encrypter
When executing build step 'Make'

The proper way to include crypto++ is NOT to download it from the website. Use terminal to get the library:

sudo apt-get install libcrypto++8 libcrypto++8-dbg libcrypto++-dev

Then check if installed on system:

apt-cache pkgnames | grep -i crypto++

Which should result with:

libcrypto++-utils
libcrypto++8
libcrypto++8-dbg
libcrypto++-dev
libcrypto++-doc

If the information above is different (which is possible if it becomes out of date), check the Crypto++ Linux wiki for instructions.

Now add the library to project with the following linkage (written as a makefile macro, but just put the -L and -I parts in the command line if you’re compiling manually):

LIBS += -L/usr/lib/crypto++ -lcrypto++
INCS += -I/usr/include/crypto++

While is is rather specific, someone out there is probably searching for this so here ya go!

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!

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