Archive for the ‘ General Coding Techniques ’ 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.

Android: What does “Volatile” mean?

At work, I’m currently working on a very large project, and a lot of it was previously written by some very experienced programmers, far beyond my level of skill. When I read through it, I often come across weird things I’ve never seen before (a lot of which gives me the content to post here!) One of these I cam across recently was this word:

volatile

Its a strange prefix to a variable name, and the first few times I looked it up, I was not able to find a clear or concise answer. When I try to compile it into simple programs, it never yielded any visible differences. I have found this article from Javamex which put together a rather simple table and explanation of what it actually does.

Essentially, volatile is used to indicate that a variable’s value will be modified by different threads.

Briefly, I can tell you it is related to threads and synchronization, so if your programs don’t have a lot of multi thread functionality, this keyword *probably doesn’t affect you. Check out the article here and feel free to toss in any comments to shed light some more light for our readers!

-Kevin Grant

Android: Getting screen pixel size and dimensions

In one of our programs, I hackishly figured out how to get screen size based off of measuring a view in the onDraw() method and only doing it the first onDraw, and blah yada blah etc. This was terrible and I knew it from the beginning, but it works, so whatever. However, I have run into the same problem into a different project and that method won’t work here, so I researched it again. Low and behold, it was much easier that I ever thought (just like everything else).

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);

and now you can access everything you want through this “metrics” variable. Found this right on the android site under Display Metrics

-Kevin Grant

Android: Ain’t no Callerback grl… (Callback functions in Android)

When I learned about callback functions in Android, it literally created a whole new world of possibilities of what I could do withing my apps. For so long I had used callback functions without even knowing it! An example of a callback function we all already use is with buttons and the onClickListener(). Usually when you create a button, you register a listener, and then you put code into it, like so:

Button btn = (Button) findViewById(yada_yada_yada);
btn.setOnclickListener(new OnClickListener(){
	@Override
	public void onClick(View v){
		// do something
	}
});

Basically, whenever you press a button, it sends a callback to this listener you set, and your program can do whatever you want in here. What we want to do now is replicate this sort of callback, but not for a button press. We want to replicate this for ANYTHING! In the example code I provide, we can now do things like this:

rst = new RandomSenderThingy();
rst.setRandomThingyListener(new RandomSenderThingyListener(){
	@Override
	public void onBoolThingChanged(boolean changed) {
		Log.d("DEBUG","Callback Received! It is: " + changed);
	}
});

The example code makes use of a few various techniques to get the point across, but I’ve clearly commented the parts that you will need to inject into your own code to get this functionality. Good luck and post any questions or comments in the comments section!

Download the source code here

-Kevin Grant

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

Formatting and Styling Strings (C/C++)

So, talking about formatting and styling strings for Java/Android has got me thinking about formatting and styling strings for C/C++. For C/C++, we use printf and sprintf. Both printf and sprintf work exactly the same except sprintf puts the output to a character array and printf puts the output to standard output (such as the console/terminal).

If you just want to put a line out to standard output, you’d write something like this:

printf("Hello World!\n");

If you want to output strings and numbers, you’d use it like this:

float freqMHz = 100.2578;
printf("%-30s: %5.2f MHz\n", "Frequency", freqMHz);

The previous example is a bit more advanced, but that’s probably as advanced as it gets. %-30s means the first parameter is a string (the “s”) and we want to allot 30 spaces for the string and left align it (the “-“). The %5.2f means the second parameter is a float and we want to format it such that we want 5 digits for the integer part with a 2 digit precision for the decimal part. The string sent to standard output would be as follows:

Frequency:                    100.26 MHz

Note that the float gets rounded up when it is formatted. For sprintf, the syntax is the same, except we add a character array to the parameters. The character array is where we would save the final string. For example, the following code will output the exact same thing as the above example:

char* outputStr = new char[1024];
sprintf(outputStr, "%-30s: %5.2f MHz\n", "Frequency", freqMHz);
printf(outputStr);

The cool thing about printf and sprintf is that you can add as many parameters as you want to the formatted string. The useful thing about printf and sprintf is that you can mix and match data types (like in the previous examples) without having to do typecasting or using (with cout) to get it to look nice. You can even format numbers to hexadecimal or scientific notation! Pretty slick, right?

Also, remember to add a newline character (“\n”) to the end of the string. It will run the next printf on the same line as the previous printf if you don’t.

Anyways, for all the different flags you can use to format printf and sprintf, check out the documentation at cplusplus.com.