espressif / esp-azure

SDK to connect ESP8266 and ESP32 to Microsoft Azure IoT services
176 stars 92 forks source link

Example iothub_client_sample_mqtt crash (CA-251) #129

Open Lisa999 opened 1 year ago

Lisa999 commented 1 year ago

This code in file iothub_client_sample_mqtt.c will lead to a crash:

static void SendConfirmationCallback(IOTHUB_CLIENT_CONFIRMATION_RESULT result, void* userContextCallback)
{
    EVENT_INSTANCE* eventInstance = (EVENT_INSTANCE*)userContextCallback;
    size_t id = eventInstance->messageTrackingId;

    if (result == IOTHUB_CLIENT_CONFIRMATION_OK) {
        (void)printf("Confirmation[%d] received for message tracking id = %d with result = %s\r\n", callbackCounter, (int)id, MU_ENUM_TO_STRING(IOTHUB_CLIENT_CONFIRMATION_RESULT, result));
        /* Some device specific action code goes here... */
        callbackCounter++;
    }
    IoTHubMessage_Destroy(eventInstance->messageHandle);
}

The problem is the IoTHubMessage_Destroy call in the end when the function is called with result IOTHUB_CLIENT_CONFIRMATION_BECAUSE_DESTROY . The callback is going to destroy the message also, leading to corrupted memory...

The correct code:

static void SendConfirmationCallback(IOTHUB_CLIENT_CONFIRMATION_RESULT result, void* userContextCallback)
{
    EVENT_INSTANCE* eventInstance = (EVENT_INSTANCE*)userContextCallback;
    size_t id = eventInstance->messageTrackingId;

    if (result == IOTHUB_CLIENT_CONFIRMATION_OK) {
        (void)printf("Confirmation[%d] received for message tracking id = %d with result = %s\r\n", callbackCounter, (int)id, MU_ENUM_TO_STRING(IOTHUB_CLIENT_CONFIRMATION_RESULT, result));
        /* Some device specific action code goes here... */
        callbackCounter++;
    }
    if (result != IOTHUB_CLIENT_CONFIRMATION_BECAUSE_DESTROY)
        IoTHubMessage_Destroy(eventInstance->messageHandle);
}