lundi 25 novembre 2019

C++ Segmentation fault while dereferencing a void pointer to a vector

#include <iostream>
#include <vector>
#include <mutex>

struct STRU_Msg
{
    std::string name;
    void *vpData;
};

class CMSG
{
public:
    template <typename T>
    int miRegister(std::string name)
    {
        STRU_Msg msg;

        msg.name = name;
        msg.vpData = malloc(sizeof(T));
        msgtable.push_back(msg);

        std::cout << "registeratio ok\n";
        return 0;
    }

    template <typename T>
    int miPublish(std::string name, T tData)
    {
        for (int i = 0; i < msgtable.size(); i++)
        {
            if (!name.compare(msgtable[i].name))
            {
                (*(T *)msgtable[i].vpData) = tData;
                std::cout << "SUccess!\n";
                return 0;
            }
            else
            {
                std::cout << "cannot find\n";
                return 0;
            }
        }
    }

private:
    std::vector<STRU_Msg> msgtable;
};


int main()
{
    CMSG message;
    std::string fancyname = "xxx";
    std::vector<float> v;

    // message.miRegister< std::vector<float> >(fancyname);
    // for (int i = 0; i < 1000; i++)
    // {
    //     v.push_back(i);
    // }
    // std::cout << "v[0]: " << v[0] << ", v[-1]: " << v[v.size()-1] << '\n';
    // message.miPublish< std::vector<float> >(fancyname, v);

    for (int i = 0; i < 1000; i++)
    {
        v.push_back(i);
    }
    std::cout << "v[0]: " << v[0] << ", v[-1]: " << v[v.size()-1] << '\n';
    message.miRegister< std::vector<float> >(fancyname);
    message.miPublish< std::vector<float> >(fancyname, v);

    return 0;
}

What I want to achieve is to write a simple publish/subscribe (like ROS) system, I use void pointer so that it works for all data type. This is the simplified code.

If I publish an int, it works fine, but what really confuse me are:

  1. If I pass a long vector (like this code), it gave me the "segmentation fault (core dump)" error.
  2. If I define the vector between "register" and "publish" (i.e. like the commented part), this error goes away.
  3. If I use a shorter vector, like size of 10, no matter where I define it, my code run smoothly.

I use g++ in Linux.

Please help me fix my code and explain why above behaviors will happen, thanks in ahead!

Aucun commentaire:

Enregistrer un commentaire