{"thread":{"id":"9005","subject":"memory inefficiency in builtin-commit-tree.c - add_buffer() - in git version 1.5.2","startedAt":"2007-07-12T16:35:13Z","lastAt":"2007-07-12T16:35:13Z","messageCount":1,"participants":["Tim Stewart"],"isPatch":false,"patchVersion":null,"patchTotal":null},"messages":[{"id":"47175","messageId":"23f4d5c70707120935k7a784f59rb3bb27ac76cb52b7@mail.gmail.com","threadId":"9005","inReplyTo":"23f4d5c70707120933l1d1664adgd12042a35f4629cd@mail.gmail.com","subject":"memory inefficiency in builtin-commit-tree.c - add_buffer() - in git version 1.5.2","fromName":"Tim Stewart","fromEmail":"tim.j.stewart@gmail.com","sentAt":"2007-07-12T16:35:13Z","receivedAt":"2007-07-12T16:35:13Z","isPatch":false,"sender":{"key":"tim.j.stewart@gmail.com","avatar":null},"body":"The function init_buffer allocates 16,384 bytes.  This function then\nsets the size of the buffer at 0 bytes.\n\nThen when add_buffer is called, it calculates how much memory the\nadded bytes will take up here:\n\n        alloc = (size + 32767) & ~32767;\n\nSince size is 0, alloc will be 0.  So the next line:\n\n         if (newsize > alloc) {\n\nwill always evaluate to true (unless newsize is 0) and then the\nfunction reallocs the buffer at twice it's current size.\n\nThis all but guarantees that the memory allocated in init_buffer will\nbe realloc'ed.\n\nHere is the code for your reference:\n\nstatic void init_buffer(char **bufp, unsigned int *sizep)\n{\n        *bufp = xmalloc(BLOCKING);\n        *sizep = 0;\n}\n\nstatic void add_buffer(char **bufp, unsigned int *sizep, const char *fmt, ...)\n{\n        char one_line[2048];\n        va_list args;\n        int len;\n        unsigned long alloc, size, newsize;\n        char *buf;\n\n        va_start(args, fmt);\n        len = vsnprintf(one_line, sizeof(one_line), fmt, args);\n        va_end(args);\n        size = *sizep;\n        newsize = size + len + 1;\n        alloc = (size + 32767) & ~32767;\n        buf = *bufp;\n        if (newsize > alloc) {\n                alloc = (newsize + 32767) & ~32767;\n                buf = xrealloc(buf, alloc);\n                *bufp = buf;\n        }\n        *sizep = newsize - 1;\n        memcpy(buf + size, one_line, len);\n}\n"}]}