简体   繁体   中英

Run-Time Check Failure #2 - Stack around the variable '' was corrupted

I have started to experiment with dlls and came across this problem. I have 2 solutions (VS 2012) 1. Where I generate the dll (contains: templatedll.h, templatedll.cpp, templatedllshort.h) 2. Where I test it (I use therefore templatedllshort.h)

So this is the code of my first (dll) solution

templatedll.h

class __declspec(dllexport) Echo
{
private:
    int output;
    void echo_private();

public:
    Echo();
    Echo(int output_);
    ~Echo();
    void echo_public();
};

templatedll.cpp

#include "templatedll.h"
#include <iostream>

Echo::Echo()
{
    output = 0;
    std::cout << "Echo()\n";
}

Echo::Echo(int output_)
{
    this->output = output_;
    std::cout << "Echo(int)\n";
}

Echo::~Echo()
{
    std::cout << "~Echo()\n";
}

void Echo::echo_private()
{
    std::cout << "this is output: " << this->output << std::endl;
}

void Echo::echo_public()
{
    echo_private();
}

templatedllshort.h (this is a short header that hides all the private parts of my class)

class __declspec(dllimport) Echo
{
public:
    Echo();
    Echo(int output_);
    ~Echo();
    void echo_public();
};

The second solution where I test it

#include "templatedllshort.h"

int main()
{
    Echo e(1);  
    e.echo_public();
    return 0;
}

Everything is properly linked and both solutions compile and run. The Run-Time Check Failure comes after return 0; statement. This is the expected output:

Echo(int)
this is output: 1
~Echo()

Can any one see where the problem is? Thanks

The problem comes from #include "templatedllshort.h" . You can not "hide" private information like this. Can you use #include "templatedll.h" and check that you don t face anymore this problem?

(this is a short header that hides all the private parts of my class)

That's fatal. The client code of your DLL will pass the wrong size to the allocator to create the object. And create an object that's too small. In this particular case, it will not reserve enough stack space for the object. The DLL itself will now scribble to memory that wasn't allocated. The /RTC warning was designed to keep you out of this kind of trouble.

Don't lie about classes.

Use an interface and a factory function to hide the implementation details.

I think you need to use the same header for both the DLL and the driver application. Also, I don't see where you're importing the DLL in the driver app.

在每个源文件中,类的定义必须相同,否则它是未定义的行为。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM