My first comment!

May 30, 2011

Nice, just got my first blog comment. And it’s not from a person I know, it’s not spam, and it’s positive!

Thank you!

Nokia lays off 7000

April 27, 2011

According to E24 Nokia is cutting down it’s workforce with 7000 persons world wide. Around 3000 of these will move to Accenture as a direct effect of Nokia abandoning Symbian.

How to handle dynamic memory in base- and derived classes

April 12, 2011

Assume that you want to write an abstract base class which uses dynamic memory allocation. It may look something like this:

class BaseClass
{
private:
    char* aString;
protected:
    const char* getString() const { return aString; }
public:
    BaseClass();
    BaseClass(const char* str);
    BaseClass(const BaseClass& b);
    virtual ~BaseClass();
    BaseClass& operator=(const BaseClass& b);
    virtual void printString() const = 0;
};

You then write the constructors, the desctructor, and the operator overloading method for ‘=’:

BaseClass::BaseClass()
{
    aString = new char[1];
    aString[0] = '';
}
BaseClass::BaseClass(const char* str)
{
    int len = strlen(str) + 1;
    aString = new char[len];
    strcpy_s(aString, len, str);
}
BaseClass::BaseClass(const BaseClass& b)
{
    int len = strlen(b.aString) + 1;
    aString = new char[len];
    strcpy_s(aString, len, b.aString);
}
BaseClass::~BaseClass()
{
    delete [] aString;
}
BaseClass& BaseClass::operator=(const BaseClass& b)
{
    if (this != &b)
    {
        delete [] aString;
        int len = strlen(b.aString);
        aString = new char[len];
        strcpy_s(aString, len, b.aString);
    }
    return *this;
}

Ok great. So now let’s create a derived class – which also uses dynamic memory allocation – from the base class:

class DerivedClass : public BaseClass
{
private:
    char* anotherString;
public:
    DerivedClass();
    DerivedClass(const char* baseString, const char* derivedString);
    DerivedClass(const DerivedClass& d);
    ~DerivedClass();
    DerivedClass& operator=(const DerivedClass& d);
    void printString() const;
};

Let’s see how these methods can be implemented:

DerivedClass::DerivedClass() : BaseClass()
{
    anotherString = new char[1];
    anotherString[0] = '';
}
DerivedClass::DerivedClass(const char* baseString, const char* derivedString) : BaseClass(baseString)
{
    int len = strlen(derivedString) + 1;
    anotherString = new char[len];
    strcpy_s(anotherString, len, derivedString);
}
DerivedClass::DerivedClass(const DerivedClass& d) : BaseClass(d)
{
    int len = strlen(d.anotherString) + 1;
    anotherString = new char[len];
    strcpy_s(anotherString, len, d.anotherString);
}
DerivedClass::~DerivedClass()
{
    delete [] anotherString;
}
DerivedClass& DerivedClass::operator=(const DerivedClass& d)
{
    if (this != &d)
    {
        delete [] anotherString;
        BaseClass::operator=(d);
        int len = strlen(d.anotherString) + 1;
        anotherString = new char[len];
        strcpy_s(anotherString, len, d.anotherString);
    }
    return *this;
}
void DerivedClass::printString() const
{
    std::cout << "Base string: " << getString() << '\n'
        << "Derived string: " << anotherString;
}

As you can see all constructors for the derived class calls the constructors for the base class. This is not always necessary but if you don’t call a base constructor explicitly the default constructor for the base class will be called. In the above example  BaseClass(baseString) calls the base constructor BaseClass(const char* str) and creates the base part of the object. But what about BaseClass(d)? As you can see d is a reference to an object of the derived class, but there is no constructor in the base class that takes such a reference as argument. So, which constructor will be used? The answer is BaseClass(const BaseClass& b). This might feel a bit odd at first, but if you think about it for a while, the object of the derived class has all the properties of the base class, so it’s perfect to use the BaseClass copy constructor to copy the BaseClass parts and then add the parts which are specific for the derived class.

The destructor only needs to free the memory allocated for anotherString. The constructor for the base class will be called automatically.

Then there’s the assignment operator. As you can see the code looks pretty much like the code for the base class, except for the line BaseClass::operator=(d);. This line handles the assignment of the base class parts of the object. Important: you explicitly need to call the BaseClass version of the assignment operator method. You can’t write *this = d; instead of BaseClass::operator=(d); since that would create a recursive call to the assignment operator method of the derived class.

There are quite a lot more that can be written on this topic. But the above text and code covers some quite important aspects. I’ve said it before and I’ll say it again: handling memory dynamically is tricky and there are a lot of pitfalls.

Code on!

Const members in a class

April 4, 2011

Assume you wish to have a const int as a member of your class, you declare your class like this:

class ClassWithConst
{
private:
    const int constInteger;
    int nonConstInteger;
public:
    ClassWithConst();
    ClassWithConst(int n, int m);
    const int getConstInt() { return constInteger; }
    int getNonConstInteger() { return nonConstInteger; }
};

Now, how do you write your constructors in order to set your const int when creating the object?
You might try this:

ClassWithConst::ClassWithConst()
{
    constInteger = nonConstInteger = 0;
}
ClassWithConst::ClassWithConst(int n, int m)
{
    constInteger = n;
    nonConstInteger = m;
}

But this will not work! Why? Since constInteger is declared as const and cannot be assigned a value in the construction block.

So what to do? Well, there’s a special syntax in C++ to assign values to const members when creating an object:

ClassWithConst::ClassWithConst() : constInteger(0)
{
    nonConstInteger = 0;
}
ClassWithConst::ClassWithConst(int n, int m) : constInteger(n)
{
    nonConstInteger = m; 
}

If you have several const members you just add them like this:

ClassWithSeveralConsts::ClassWithSeveralConsts() : constInt(0), constDouble(0.0), constChar('a')
{
    nonConstInteger = 0;
    nonConstDouble = 0.0;
    nonConstChar = 'a';
}

Code on!

Pitfalls when using classes with dynamic memory allocation

April 2, 2011

Already familiar with the “Rule of three”, coined by Marshall Cline in 1991? Then you probably can stop reading here. Otherwise, please go on.

Let’s start with an example. Assume you have the following class:

class MyClass
{
private:
    char aString[80];
public:
    MyClass();
    MyClass(char* s); 
};

Your program works fine, but then you decide to implement dynamic memory allocation for aString so you change the class like this:

class MyClass
{
private:
    char* aString;
public:
    MyClass();
    MyClass(char* s);
    ~MyClass();
}

And then you change the constructors and the destructor to look like this:

MyClass::MyClass()
{
    aString = 0;
}
MyClass::MyClass(char* s)
{
    int len = strlen(s) + 1;
    aString = new char[len];
    strcpy_s(aString, len, s);
} 
MyClass::~MyClass()
{
    delete [] aString;
}

Now, this might look ok and it will compile without any errors or warnings. But lets look at some examples on what happens when you use this class.

Example 1, creating an object:

MyClass myObject; // Calls the default constructor

This calls the default constructor, which sets the aString-pointer to zero (nullpointer). And then calls the destructor when destroying the object. No problems here.

Example 2, calling the 2:nd constructor:

MyClass myObject = MyClass("A string goes here");

This calls the 2:nd constructor. This also works without a problem.

Example 3, calling a function with an object as argument:

void myFunction(MyClass myObject);
int main()
{
    MyClass myObject = MyClass("A string goes here");
    myFunction(myObject);

    return 0;
}
void myFunction(MyClass myObject)
{
    // dummy
}

Now, the code will still compile without errors or warnings, BUT, this program contains a bug and is likely to crash!

To understand why we need to look at what happens when myFunction is called. Since the argument isn’t a pointer or a reference, a copy of myObject will be created when entering the function. And, when the exiting the function, the copy will be destroyed and the destructor will be called. But which one of the constructors is used when creating the copy? The answer is none of them!

What happens is that the compiler searches for a copy constructor and when one isn’t found, it creates one. The basic declaration of the copy constructor looks like this:

MyClass::MyClass(const MyClass&);

The generated copy constructor copies the values for all members of the original object to the copy. This means that the aString pointer of the copy is assigned the value of the original aString pointer, and therefore both the pointers now points at the memory area holding the original string. Then when the function exits the copy is destroyed and the memory, still holding the original string, is deallocated. The function call actually destroyed the original object!

The remedy here is to write your own copy constructor and have your program use that instead of a generated one (declaration as above):

MyClass::MyClass(const MyClass& copyThisObject)
{
    if (copyThisObject.aString == 0)
        aString = 0;
    else
    {
        int len = strlen(copyThisObject.aString) + 1;
        aString = new char[len];
        strcpy_s(aString, len, copyThisObject.aString);
    }
}

Great! Now it should be safe to call a function (or in some other way trigger a copy of an object). All done? Not exactly, look at the following example.

Example 4, assigning one object to another:

MyClass anObject = MyClass("A string goes here");
MyClass anotherObject;
anotherObject = anObject;

By doing this a bug introduced in the program.  When using the ‘=’ operator the aString pointers for both objects will end up pointing at the same section in memory. When one of the objects is destroyed the other one end up having a pointer which points to memory that has already been deallocated. And when the second object is destroyed the program will try to deallocate the same memory again, which may crash the application. So what’s the cure doctor? Well, what needs to be done here is to overload the ‘=’ operator with a version that does what we want it to do:

class MyClass
{
    ...
public:
    ...
    MyClass& operator=(const MyClass&);
};
MyClass& MyClass::operator=(const MyClass& myObject)
{
    if (this != &myObject) // Protects against 'myObject = myObject'
    {
        delete [] aPointer;
        int len = strlen(myObject.aPointer) + 1;
        aPointer = new char[len];
        strcpy_s(aPointer, len, myObject.aPointer);
    }
    return *this;
}

Now it’s done! Takes quite a lot of work to change a fixed size char array to a char pointer doesn’t it?

More info?

Check out the following wikipedia links which explains these things quite thorough:

Rule of three:
http://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming)
Destructor:
http://en.wikipedia.org/wiki/Destructor_(computer_science)
The copy constructor:
http://en.wikipedia.org/wiki/Copy_constructor
Assignment operator:
http://en.wikipedia.org/wiki/Assignment_operator_in_C%2B%2B

Linked list next pointer mishap

March 24, 2011

Assume a linearly-linked list. The list has a property firstNode which points at the first node in the list (or NULL if the list is empty).

Each node has two properties, a value, and a pointer next which points to the next node in the list (or NULL if the node is the last one in the list).

Now assume that you wish to add a new node at the end of the list. First you need to create a new node object:

Node* List::createNewNode(listItem value)
{ 
    Node* newNode = new Node();
    newNode->value = value;
    newNode->next = NULL;

    return newNode;
}

Then you need to insert the new node at the end of the list:

void List::insertNodeAtEnd(listItem value) 
{
    newNode = createNewNode(value);
    if (this->isEmpty())
    {
        this->firstNode = newNode;
    }
    else
    {
        Node* lastNode = this->firstNode;
        while (lastNode->next != NULL)
            lastNode = lastNode->next;
        lastNode->next = newNode; 
    } 
}

The above code should work fine. But then I thought, what if I do this:

void List::insertNodeAtEnd(listItem value) 
{
    newNode = createNewNode(value);
    if (this->isEmpty())
    {
        this->firstNode = newNode;
    }
    else
    {
        Node* lastNode = this->firstNode->next;
        while (lastNode != NULL)
            lastNode = lastNode->next;
        lastNode = newNode;
    } 
}

Shouldn’t that do the same thing? lastNode = lastNode->next followed by lastNode = newNode should be the same as lastNode->next = newNode, shouldn’t it?

Initially I was surprised when I found that this didn’t work. Can you figure out what’s wrong?

To answer the question:
In the first version, the lastNode pointer points to the last node in the list after the while loop. Then, by using the -> operator the next pointer of the last node is set to point at the new node.
But in the second version, the lastNode pointer points to NULL after the while loop. It is then set to point at the new node. This does not change the next pointer for the last node in the list, which will still point to NULL after exiting the method! It can actually be written like this:

Node* lastNode = this->firstNode->next;
lastNode = NULL;
lastNode = newNode;

Quite obvious that the above code doesn’t do the work, isn’t it?

Pointers – const int* or int* const?

March 15, 2011

Assume the following code:

int n = 1;
const int* p1 = &n;
int* const p2 = &n;

What is the difference between the two pointers?

Try this:

*p1 = 2; // Error
*p2 = 2; // Ok

And this:

int m = 1;
p1 = &m; // Ok
p2 = &m; // Error

The answer is that when declaring a pointer like p1 you say that the value that the pointer points to can’t be modified using the pointer while when declaring a pointer like p2 you say that the pointer can’t be modified.

So, what happens if you do this:

int* const p;

Well, then you have an undefined integer pointer which can’t be set to point anywhere useful.

The many pitfalls of allocating memory dynamically

March 9, 2011

After working almost exclusively with development in Python for the last year I had forgotten how easy it is to make a mistake in C/C++ when it comes to allocating/freeing up memory dynamically.

Currently I’m using some of my spare time to refresh my memory on the C++-syntax. Just did an exercise where you are supposed to allocate memory for a vector of structs, loop through the structs in the vector by incrementing the pointer to the elements in the vector and then free up the memory.

My first mistake was simple, I forgot to include the delete statement. Then I forgot to add braces ‘[]’ after the delete keyword. And finally I forgot to reset the pointer to point at the first element in the vector before trying to delete it. In all cases the code compiled without warnings or errors.

Here are the consequences:

  1. Forgetting to include a delete statement: allocated memory will stay reserved, may introduce a memory leak.
  2. Forgetting to include ‘[]’ in the delete statement when using ‘[]’ in the new statement: unspecified. In my case the program crashed.
  3. Forgetting to reset the pointer: the program will try to free memory beyond the memory that has been allocated. In my case this caused the program to crash.

The above text describes a few pitfalls when using dynamic memory allocation, I’m sure there are many more.

What people want in Nokia’s Windows based smartphones

February 28, 2011

According to the news site IDG Nokia is having trouble to firmly establish the co-operation with Microsoft.

On their blog Nokia recently had a poll where visitors could answer the question “Which feature in Windows Phone are you looking forward to the most?”. The most popular answer was “Something else” (23%) followed by “A unique GUI” (22%). Xbox-gaming, Windows Integration, and Internet Explorer were not very popular choices. The least anticipated feature was Microsoft Silverlight with only 3% of the votes.

Embedded C#?

February 25, 2011

From time to time I scan through the job ads for the area where I live and I find that there are a lot of Java and C#/.NET developers wanted. This has got me wondering if it’s a good idea to start-up some small C# projects at home.

Since I like to have some external hardware running, not only write some apps that will run locally on the PC, I started searching the net for some information on C# in embedded devices. On msdn I soon found a description on the Microsoft .NET Micro Framework which supports ARM7- and ARM9-based processors.

I continued on to ARM’s website to try to find some more information. Unfortunally I couldn’t find any information on the .NET Micro Framework there. Linked from ARM’s website I did find the ARM Development Tools which only lists the C/C++ compiler.

I will try to search for some more information on the .NET Micro Framework. But I have a feeling that C/C++ (and even some Asssembler) are the languages for the embedded community, and will be so for quite some time.