Checking file signature

Find below a post on the topic of file signatures, also known as Magic Numbers. The provided code snippet contains an error for the reader to discover and point out.

class MagicMixin { // Mixin for checking the magic number
        virtual bool chkMagic 
          (const std::string &filename) const {
            // full implementation snipped..
            std::string magic = getMagic();
              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;

Short 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 actual header of 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 follows the correct format (by invoking the aforementioned chkMagic).

The error in the provided code lies in the indirect invocation of a virtual function during the construction of MP3File, which will cause a pure virtual function call in run time. Further explanation can be found in this post.

2 thoughts on “Checking file signature

  1. 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.

Leave a Reply