lundi 22 octobre 2018

using Poco::JSON::Object in dynamic library

I'm trying to build a dynamic library in which I used Poco::JSON library.

// 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;
}

Then, using the command to build the dynamic library "libmymath.so":

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

// test file

#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;
}

compile command:

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

When I ran the main.test, I got an error:

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

Why it happens? If I moved the declaration "Poco::JSON::Object obj;" in function "math::sum" into the constructor "math::math", it won't happen.

Aucun commentaire:

Enregistrer un commentaire