eclipse-mosquitto / mosquitto

Eclipse Mosquitto - An open source MQTT broker
https://mosquitto.org
Other
9.07k stars 2.39k forks source link

Question About how to user "mosquitto_broker_publish" #3146

Open luckychengww opened 1 week ago

luckychengww commented 1 week ago

I'm going to develop a plugin using "mosquitto_broker_publish" function, but it casue mosquitto broker "Segmentation fault" after client connect. But when i use "mosquitto_broker_publish_copy" function instead,it's went ok. what's the reasion?

Below is my plugin code

static int callback_message(int event, void *event_data, void *userdata)
{
    UNUSED(event);
    UNUSED(userdata);
    UNUSED(event_data);

    int result_code = mosquitto_broker_publish(NULL, "/broker/publish", strlen("test-message"), "test-message", 0, true, NULL);
    return MOSQ_ERR_SUCCESS;
}
ralight commented 1 week ago

I can see this needs clarifying in the documentation for the function, it's not at all clear.

mosquitto_broker_publish_copy() takes a copy of the payload, whereas mosquitto_broker_publish() takes ownership of the payload, meaning that it will later free it and it must be allocated on the heap. In your case, "test-message" is not allocated on the heap, so when the broker later tries to free it, there is a crash

luckychengww commented 6 days ago

I can see this needs clarifying in the documentation for the function, it's not at all clear.

mosquitto_broker_publish_copy() takes a copy of the payload, whereas mosquitto_broker_publish() takes ownership of the payload, meaning that it will later free it and it must be allocated on the heap. In your case, "test-message" is not allocated on the heap, so when the broker later tries to free it, there is a crash

thank you very much