threads / discuss / 9005

memory inefficiency in builtin-commit-tree.c - add_buffer() - in git version 1.5.2

Subject: memory inefficiency in builtin-commit-tree.c - add_buffer() - in git version 1.5.2

## tl;dr

One message between Jul 12, 2007 and Jul 12, 2007.

replies: 0people: 1as markdown or json

Tim Stewart· Jul 12, 2007, 16:35 UTC · lore

The function init_buffer allocates 16,384 bytes. This function then sets the size of the buffer at 0 bytes.

Then when add_buffer is called, it calculates how much memory the added bytes will take up here:

        alloc = (size + 32767) & ~32767;
Since size is 0, alloc will be 0.  So the next line:
         if (newsize > alloc) {

will always evaluate to true (unless newsize is 0) and then the function reallocs the buffer at twice it's current size.

This all but guarantees that the memory allocated in init_buffer will be realloc'ed.

Here is the code for your reference:
static void init_buffer(char **bufp, unsigned int *sizep)
{
        *bufp = xmalloc(BLOCKING);
        *sizep = 0;
}
static void add_buffer(char **bufp, unsigned int *sizep, const char *fmt, ...)
{
        char one_line[2048];
        va_list args;
        int len;
        unsigned long alloc, size, newsize;
        char *buf;
        va_start(args, fmt);
        len = vsnprintf(one_line, sizeof(one_line), fmt, args);
        va_end(args);
        size = *sizep;
        newsize = size + len + 1;
        alloc = (size + 32767) & ~32767;
        buf = *bufp;
        if (newsize > alloc) {
                alloc = (newsize + 32767) & ~32767;
                buf = xrealloc(buf, alloc);
                *bufp = buf;
        }
        *sizep = newsize - 1;
        memcpy(buf + size, one_line, len);
}

← back to recent threads