审查生成的字节缓冲区

来自 C 动态内存管理
C23 (GCC 13.3.0) 高级 6分钟 找出 4处问题

根据任务契约审查这个生成的可增长缓冲区。

追加任意字节;失败时保留完整旧缓冲区;拒绝无效输入并防止大小溢出;销毁后留下可复用的空状态。

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);
}

生成代码仅作示例,不代表任何特定模型

在试验场中打开
报告错误