Review a generated byte buffer

from C dynamic memory management
C23 (GCC 13.3.0) advanced 6 min 4 issues to find

Review this generated growable buffer against the requested contract.

Append arbitrary bytes while preserving the complete old buffer on failure, reject invalid input, prevent size overflow, and leave a destroyed buffer in a reusable empty state.

C
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
    unsigned char *data;
    size_t length;
    size_t capacity;
} Buffer;

int buffer_append(Buffer *buffer, const unsigned char *input, size_t count) {
    size_t needed = buffer->length + count;

    if (needed > buffer->capacity) {
        buffer->capacity = needed * 2;
        buffer->data = (unsigned char *)realloc(buffer->data, buffer->capacity);
    }

    memcpy(buffer->data + buffer->length, input, count);
    buffer->length = needed;
    return 1;
}

void buffer_destroy(Buffer *buffer) {
    free(buffer->data);
}

generated code is illustrative, not from any one model

Open in playground
Report an error