Re: [PATCH v2 3/4] strbuf_setlen: don't write to strbuf_slopbuf
- From
Brandon Casey <drafnel@gmail.com>
- Date
- Aug 23, 2017, 21:20 UTC
- Message-ID
- <CA+sFfMe56itAMDXOJybf0yHj+BqU1Ai1aU7inoTG3FJtdtZxyw@mail.gmail.com>
- In-Reply-To
- <xmqqh8wyxag1.fsf@gitster.mtv.corp.google.com>
On Wed, Aug 23, 2017 at 2:04 PM, Junio C Hamano <gitster@pobox.com> wrote:
Show 8 quoted lines
> Brandon Casey <drafnel@gmail.com> writes: > >> So is there any reason why didn't do something like the following in >> the first place? > > My guess is that we didn't bother; if we cared, we would have used a > single instance of const char in a read-only segment, instead of > such a macro.
I think you mean something like this:
const char * const strbuf_slopbuf = "";
..with or without "const" at the beginning. We can't use an actual variable like that since we also want to be able to do initialization like:
struct strbuf b = STRBUF_INIT;
i.e.
struct strbuf b = { 0, 0, strbuf_slopbuf };So the compiler needs to be able to determine that everything within the curly braces is constant and apparently gcc cannot.
On a related note... I was just looking at object.c which also uses a slopbuf. We could similarly protect it from inadvertent modification by doing something like this:
diff --git a/object.c b/object.c index 321d7e9..4c7a041 100644 --- a/object.c +++ b/object.c @@ -303,7 +303,7 @@ int object_list_contains(struct object_list *list, struct ob ject *obj) * A zero-length string to which object_array_entry::name can be * initialized without requiring a malloc/free. */ -static char object_array_slopbuf[1]; +static const char * const object_array_slopbuf = ""; void add_object_array_with_path(struct object *obj, const char *name, struct object_array *array, @@ -326,7 +326,7 @@ void add_object_array_with_path(struct object *obj, const char *name, entry->name = NULL; else if (!*name) /* Use our own empty string instead of allocating one: */ - entry->name = object_array_slopbuf; + entry->name = (char*) object_array_slopbuf; else entry->name = xstrdup(name); entry->mode = mode;