Checking file signature

Posted on: 27/09/2009

Okay, so here’s how this category is going to work. I will post and explain a few lines of code, with one (or more) defect(s) hidden in them. The defect will not be trivial (at least not intentionally). Your job is to spot and explain the bug(s) – once there’s at least one comment about what i was aiming for, I will update the post with an explanation.

Find below the first post, on the topic of file signatures (aka magic numbers).

class MagicMixin { // Mixin for checking the magic number
        virtual bool chkMagic (const std::string &filename) const {
            // full implementation removed for simplicity..
            std::string magic = getMagic();
            return beginning(filename, magic.size()) == magic;
        virtual std::string getMagic () const = 0;

class MP3File : protected MagicMixin { // MP3 files
        MP3File (const std::string &filename) {
            if (!chkMagic(filename))
                throw std::string(filename + " isn't an mp3.");
        // more functionality..
        virtual std::string getMagic () const { return "ID3"; }

int main () { // usage example
    MP3File m("song.mp3");
    return 0;

And a small, yet thorough, explanation:

  • MagicMixin is an implementation of the magic number checking mechanism: it requires the inheriting class to implement the pure virtual function returning the relevant magic number, which is then matched against the given file.
  • MP3File is a concrete implementation of the mp3 file format. It allows loading an mp3 file and performing some actions on it. To prevent loading of incorrect files, the MP3File verifies that the given file is indeed in the correct format (by invoking the aforementioned chkMagic).

The error was in the indirect invocation of a virtual function during the construction of MP3File, which caused a pure virtual function call in this case. Further explanation can be found in this post.


2 Responses to "Checking file signature"

The vtable is not ready until construction is done. Therefore, the call to the virtual function getMagic from MagicMixin::chkMagic results in invocation of the pure virtual method MagicMixin::getMagic, which has no body. That sounds quite bad.

Nice post.

Actually this code is okay, this is an erroneous post as it actually has no error 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 27 other followers


%d bloggers like this: