eclipse-mosquitto / mosquitto

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

Question About how to user "mosquitto_broker_publish" #3146

Open luckychengww opened 3 weeks ago

luckychengww commented 3 weeks 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 3 weeks 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 3 weeks 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