Skip to content

Payload can only be trivially copyable #134

@azza1173

Description

@azza1173

Thanks for the library!

I've been running into an issue recently with payloads. Every example described in this repo and in other issues have payloads as primitive types of some sort. For my application, I'm trying to use payloads that have std::string and std::vector etc but I get 2 different bugs when I sanitize it.


#define HFSM2_ENABLE_PLANS
#include <hfsm2/machine.hpp>

#include <string>
#include <vector>
#include <cstdio>
#include <cstring>

struct Payload
{
    // std::string label;              // stack-use-after-return
    std::vector<int> data;          // memory leak
};

struct Context {};
using M = hfsm2::MachineT<
    hfsm2::Config::ContextT<Context>::PayloadT<Payload>::TaskCapacityN<256>
>;
#define S(s) struct s
S(Root); S(StateA); S(StateB);
using FSM = M::Root<S(Root), S(StateA), S(StateB)>;

struct Root : FSM::State {};
struct StateA : FSM::State
{
    void enter(PlanControl& control)
    {
        Payload p;
        // p.label = "";
        p.data  = {1, 2, 3, 4, 5};
        control.plan().changeWith<StateA, StateB>(p);
    }

    void update(FullControl& control) { control.succeed(); }
};

struct StateB : FSM::State
{
    void enter(PlanControl& control)
    {
        const auto& transitions = control.currentTransitions();
        const Payload* p = transitions[0].payload();
        // std::string copy = p->label;
        std::printf("[StateB] data.size() = %zu, data[0] = %d\n",
            p->data.size(), p->data.empty() ? -1 : p->data[0]);
    }
};

int main(int argc, char* argv[])
{
    Context ctx;
    FSM::Instance fsm{ctx};

    fsm.update();
    fsm.update();

    return 0;
}

Switch between the 2 comments to see the stack-use-after-return and memory leak.

Compiled with gcc version 15.2.1 20260209
g++ -std=c++17 -g -O0 -fsanitize=address

Is there a way for payloads to support copy constructible types or am I doing something wrong.

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions