Skip to content

MSGPACK_DEFINE() with char arrays silently does the wrong thing #399

@vadz

Description

@vadz

Consider the following example program (please ignore the unsafe use of strncpy() etc) using msgpack 1.3.0:

#include <msgpack.hpp>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct S {
    explicit S(const char* n)
    {
        strncpy(name, n, sizeof(name));
    }

    char name[10];

    MSGPACK_DEFINE(name);
};

int main()
{
    S s("foo");

    try {
        msgpack::sbuffer sbuf;
        msgpack::pack(sbuf, s);

        msgpack::unpacked ret;
        msgpack::unpack(ret, sbuf.data(), sbuf.size());

        S s2("");
        ret.get().convert(&s2);

        if (strcmp(s.name, s2.name) == 0)
            return EXIT_SUCCESS;
    } catch (std::exception& e) {
        fprintf(stderr, "Exception: %s\n", e.what());
    }

    return EXIT_FAILURE;
}

Compiling and running it unexpectedly results in an exit failure with "bad cast" exception.

Debugging it I see that what happens is that s is correctly serialized because there is a pack<const char N> specialization. However there is no equivalent specialization for convert(), so convert<char> is used which tries to extract char, as an int, from the object containing a string and fails.

IMO this is a pretty bad bug because everything compiles just fine and even works on the server (serialization) side but then fails during run-time on the client.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions