getting args of a message - memory handling

Havoc Pennington hp at pobox.com
Sat May 24 07:23:45 PDT 2008


Hi,

On Sat, May 24, 2008 at 8:02 AM, Fritz Code <codefritz at googlemail.com> wrote:
>    //copy value of received argument and make necessary memory allocation
>    buf = (char *)malloc(sizeof(char) * (strlen(resultarg) +1));
>    strcpy(buf, resultarg);

Some general code comments here: strdup() is probably easier (though
not strictly portable), sizeof(char) is always 1, the char* cast is
not required, and malloc can return NULL.

>    return buf; //return pointer, to do anything with it, of course it still
> must be "free'ed" when Im done with it ( free() )

Yes this is correct. resultarg is just a pointer into the DBusMessage.
So when you unref the message, resultarg is no good anymore. Making a
copy as you do above is necessary.

> The adress where resultarg points to is not valid anymore after the reply
> was unrefed, right?

Yes.

> Handling reply arguments of type array is different.
> Here you don't have to allocate new memory If you want to keep the
> arguments.
> But you have to free the memory after the message reply was unrefed,
> although you haven't allocated the memory.

"String-like" arrays with dbus_message_get_args() are special, in that
dbus copies them for you. But other arrays are not copied. The reason
string-like (TYPE_STRING, TYPE_OBJECT_PATH) arrays are special is that
on the wire they are flattened out and look like one big block of
memory, but they would be a pain to use in that format.

>   //  for (i = 0; i < servicesCount; i++)
>   //   free (services[i]);
>   //  free (services);

There is a dbus_free_string_array() that will do this for you, incidentally.

Havoc


More information about the dbus mailing list