Review generated owned text message

from C structs, unions and enums
C23 (GCC 13.3.0) advanced 6 min 4 issues to find

Review this generated implementation of a cloneable, owned text message built from untrusted input.

Construct a valid owned text message, report allocation failure, and clone it without sharing ownership.

C
#include <stdlib.h>
#include <string.h>
typedef enum { MSG_NUMBER, MSG_TEXT } MessageKind;

typedef struct {
    MessageKind kind;
    union {
        int n;
        char *s;
    } as;
} Message;

Message message_from_text(const char *input, size_t length) {
    Message result = {0};
    result.kind = MSG_TEXT;
    result.as.s = malloc(length + 1u);
    if (result.as.s == NULL) return result;
    memcpy(result.as.s, input, length);
    result.as.s[length] = '\0';
    return result;
}

Message message_copy(Message source) {
    return source;
}

generated code is illustrative, not from any one model

Open in playground
Report an error