Re: [PATCH 1/6] path.c: allocate enough memory for string
- From
Stefan Beller <sbeller@google.com>
- Date
- Mar 30, 2016, 16:41 UTC
- Message-ID
- <CAGZ79kb6dsaSxQ+HaYODBurnFz3MbsisSNkdrckFZLvSCvS-JQ@mail.gmail.com>
- In-Reply-To
- <CAPig+cSqC1muy+vcmpkp9uM9T3CC4pa5jWGUot_FtrVshEAUEw@mail.gmail.com>
On Tue, Mar 29, 2016 at 5:57 PM, Eric Sunshine <sunshine@sunshineco.com> wrote:
Show 19 quoted lines
> On Tue, Mar 29, 2016 at 8:38 PM, Stefan Beller <sbeller@google.com> wrote:
>> `strlen` returns the length of a string without the terminating null byte.
>> To make sure enough memory is allocated we need to pass `strlen(..) + 1`
>> to the allocation function.
>>
>> Signed-off-by: Stefan Beller <sbeller@google.com>
>> ---
>> diff --git a/path.c b/path.c
>> @@ -155,7 +155,7 @@ static struct trie *make_trie_node(const char *key, void *value)
>> struct trie *new_node = xcalloc(1, sizeof(*new_node));
>> new_node->len = strlen(key);
>> if (new_node->len) {
>> - new_node->contents = xmalloc(new_node->len);
>> + new_node->contents = xmalloc(new_node->len + 1);
>> memcpy(new_node->contents, key, new_node->len);
>
> Huh? This is a trie. It never accesses 'contents' as a NUL-terminated
> string. Plus, no NUL is ever even copied, thus this is just
> overallocating. How is this an improvement?By using strlen, I assumed it was a standard C string. I missed that, though.
> >> } >> new_node->value = value; >> --