c++templatesspecializationstack-corruption

stack corrupted when linking to specialized templates


I just went to some really weird behavior and wondered a while what was happening.

I wrote a C++ library, containing a class MemoryBlock:

So I have two header files, one for the "concept", and one for the partial specialization.

MemoryBlock.h:

template <int Platform, typename T>
class MemoryBlock {
public:
    MemoryBlock(unsigned size);
    ~MemoryBlock();
};

and a partial specialization (which I want to stay hidden from the caller)

MemoryBlock0.h:

template <typename T>
class MemoryBlock<0, T> {
private:
    T* _data;
    unsigned _size;

public:
    MemoryBlock(unsigned size): _size(size) {
        _data = (T*) malloc(size*sizeof(T));
    }

    ~MemoryBlock() {
        free(_data);
    }
};

in a cpp file, a instanciate the templates for float and double

Instanciation.cpp

template MemoryBlock<0, double>;
template MemoryBlock<0, float>;

In a separate project, I link to the (static) lib generated by the code above, and includes the concept header

Main.cpp

#include <MemoryBlock.h>

int main(int argc, char** argv) {
   MemoryBlock<0, float> a(100);
}

This compiles and links perfectly well. However, when running, I get an error: Stack corrupted around variable "a"


Solution

  • After seaching that for a while, I decided to add the two field in the "concept" file:

    template <int Platform, typename T>
    class MemoryBlock {
    private:
        T* _data;        // must match the specialization apparently
        unsigned _size;  // must match the specialization apparently
    public:
        MemoryBlock(unsigned size);
        ~MemoryBlock();
    };
    

    And error is now fixed.

    It appears that the client project (the one referencing the lib), don't know about the internal memory representation of the partial specialization, and trusts the concept header, even if all the symbols have been statically linked.