在动态库中使用Poco :: JSON :: Object时堆栈崩溃

时间:2018-10-22 09:18:54

标签: c++ json c++11 poco-libraries stack-smash

我正在尝试构建一个动态库,在其中使用了Poco :: JSON库。

// header file
#ifndef __MATH_H__
#define __MATH_H__

#include <cstdlib>

class math
{
public:
    static math* getInstance()
    {
        if (NULL == m_pMath)
        {
            m_pMath = new math();
        }
        return m_pMath;
    }

    void releaseInstance()
    {
        if (NULL != m_pMath)
        {
            delete m_pMath;
            m_pMath = NULL;
        }
    }

public:
    int sum(int a, int b);
    int sub(int a, int b);

private:
    math();
    virtual ~math();

private:
    static math* m_pMath;
};

#endif  // __MATH_H__

// source file
#include "math.h"
#include <Poco/JSON/Object.h>

math* math::m_pMath = NULL;

math::math()
{}

math::~math()
{}

int math::sum(int a, int b)
{
    Poco::JSON::Object obj;  // if this declaration exists, I always got stack smashing
    return a + b;
}

int math::sub(int a, int b)
{
    return a - b;
}

然后,使用命令构建动态库“ libmymath.so”:

g++ math.* -std=c++11 -fPIC -shared -lPocoJSON -lPocoFoundation -g -o libmymath.so

//测试文件

#include "math.h"
#include <iostream>
using namespace std;

int main()
{
    cout << "sum: " << math::getInstance()->sum(1, 2) << endl;
    cout << "sub: " << math::getInstance()->sub(1, 2) << endl;
    return 0;
}

编译命令:

g++ main.cpp -std=c++11 -Wl,-rpath=./ -L. -lmymath -o main.test

运行main.test时,出现错误:

[ubuntu@ubuntu]$> ./main.test 
*** stack smashing detected ***: ./main.test terminated
Aborted

为什么会这样? 如果我移动了声明“ Poco :: JSON :: Object obj;”在函数“ math :: sum”中插入构造函数“ math :: math”,就不会发生。

0 个答案:

没有答案