-1

I have simpe MQTT client application from hivemq site:

MQTTClient client;
MQTTClient_create(&client, "ssl://xxx.s1.eu.hivemq.cloud:8883", "Client_1", MQTTCLIENT_PERSISTENCE_NONE, NULL);
    
int i = MQTTClient_setCallbacks(client, NULL, NULL, messageArrived, NULL);

Got segmentation fault while setting callback in variable m->c->connect_state

MQTTClient.c code with segmentation fault:

int MQTTClient_setCallbacks(MQTTClient handle, void* context, MQTTClient_connectionLost* cl, MQTTClient_messageArrived* ma, MQTTClient_deliveryComplete* dc)
{
    int rc = MQTTCLIENT_SUCCESS;
    MQTTClients* m = handle;

    FUNC_ENTRY;
    Thread_lock_mutex(mqttclient_mutex);

    if (m == NULL || ma == NULL || m->c->connect_state != NOT_IN_PROGRESS)
...
}
vico
  • 17,051
  • 45
  • 159
  • 315
  • 2
    How is this different from the question you asked yesterday? https://stackoverflow.com/questions/70101845/which-variable-cause-segmentation-fault – Lundin Nov 25 '21 at 09:45
  • 1
    You need to check the result of this `MQTTClient_create` to see if it was successful or not. – Lundin Nov 25 '21 at 09:58
  • You were already told that `m->c` might be `NULL` in your other question. You still do not check if that is the case. Why? – Gerhardh Nov 25 '21 at 10:04
  • The code is confusing: `MQTTClient` is struct. You pass the entire struct and then call it *handle*. Then you assign it to a `MQTTClients` pointer. What is the type of `MQTTClients` as opposed to `MQTTClient`? Does the code compile at all? – Codo Nov 25 '21 at 10:14
  • @Codo I raised the same concerns in that other post. Turns out it's a badly written library with `MQTTClient` being a hidden typedef for `void*`. Why they made such a bad design I have no idea. Because: open source... or something. – Lundin Nov 25 '21 at 11:45
  • @Lundin Thanks. I was looking at the embedded version of the Paho library, which is different. – Codo Nov 25 '21 at 13:06
  • @Codo I have no idea why official Paho library for C is badly written, but what I should do? What might be alternative solution in my case? – vico Nov 25 '21 at 14:01
  • 1
    The fishy assignment in `MQTTClient_setCallbacks` is not the culprit, but one of the parameters passed to that function. That's why I said you need to check the result of `MQTTClient_create` to see that it's fine. Similarly once inside `MQTTClient_setCallbacks` you should be able to inspect `m` and get the whole struct there - the member variables should be set to something that makes sense. – Lundin Nov 25 '21 at 14:07

1 Answers1

1

My function MQTTClient_create returned error (Lundin was right) since I passed connection string that requires SSL and my current library does not support SSL. So, MQTTClient was not created and I was trying to access it's field m->c->connect_state and got segmentation fault.

vico
  • 17,051
  • 45
  • 159
  • 315