运行时检查失败#2 - 变量''周围的堆栈已损坏

时间:2013-10-03 14:50:34

标签: c++ visual-studio-2012 dll

我已经开始尝试使用dll并遇到了这个问题。我有2个解决方案(VS 2012) 1.我在哪里生成dll(包含:templatedll.h,templatedll.cpp,templatedllshort.h) 2.我在哪里测试它(因此我使用templatedllshort.h)

所以这是我的第一个(dll)解决方案的代码

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(这是一个隐藏我班级所有私人部分的短标题)

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

我测试它的第二个解决方案

#include "templatedllshort.h"

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

所有内容都已正确链接,两个解决方案都可以编译运行。返回0后运行时检查失败;声明。 这是预期的输出:

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

任何人都可以看到问题所在吗? 感谢

4 个答案:

答案 0 :(得分:1)

问题来自#include "templatedllshort.h"。你不能隐藏&#34;像这样的私人信息。你可以使用#include "templatedll.h"并检查你不再面对这个问题吗?

答案 1 :(得分:1)

  

(这是一个隐藏我班级所有私人部分的短标题)

那是致命的。 DLL的客户端代码会将错误的大小传递给分配器以创建对象。并创建一个太小的对象。在这种特殊情况下,它不会为对象保留足够的堆栈空间。 DLL本身现在会乱写到未分配的内存。 / RTC警告旨在让您远离这种麻烦。

不要对课程撒谎。

使用界面和工厂功能隐藏实施细节。

答案 2 :(得分:0)

我认为您需要为DLL和驱动程序应用程序使用相同的标头。此外,我没有看到您在驱动程序应用程序中导入DLL的位置。

答案 3 :(得分:0)

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