aws-c-common icon indicating copy to clipboard operation
aws-c-common copied to clipboard

Small over allocation in each aws_string

Open giltho opened this issue 3 years ago • 0 comments

Hi !

It seems that aws_string_new_from_array is over allocating a bit of memory in each string. Because of the fact that aws_string is defined as follow :

struct aws_string {
    struct aws_allocator *const allocator;
    const size_t len;
    const uint8_t bytes[1];
};

given alignment constraints in C, sizeof (struct aws_string) is 24. The offset in a string struct denoted by str->bytes is 16 (allocator is at 0, len is at 8).

Now, aws_string_new_from_array allocates memory in the following way:

size_t malloc_size;
    if (aws_add_size_checked(sizeof(struct aws_string) + 1, len, &malloc_size)) {
        return NULL;
    }
    struct aws_string *str = aws_mem_acquire(allocator, malloc_size);
    if (!str) {
        return NULL;
    }

so it allocates 24 + length + 1 bytes, while only 16 + length + 1 bytes are needed. So every aws_string contains 8 too many bytes that will never be accessed at the end of the object. It's really not a lot, but it's an easy fix.

giltho avatar Mar 12 '21 14:03 giltho