Skip to content

Commit e945178

Browse files
rscharfegitster
authored andcommitted
avoid pointer arithmetic involving NULL in FLEX_ALLOC_MEM
Calculating offsets involving a NULL pointer is undefined. It works in practice (for now?), but we should not rely on it. Allocate first and then simply refer to the flexible array member by its name instead of performing pointer arithmetic up front. The resulting code is slightly shorter, easier to read and doesn't rely on undefined behaviour. NB: The cast to a (non-const) void pointer is necessary to keep support for flexible array members declared as const. Signed-off-by: Rene Scharfe <[email protected]> Reviewed-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent ddd0bfa commit e945178

File tree

1 file changed

+3
-2
lines changed

1 file changed

+3
-2
lines changed

git-compat-util.h

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -815,8 +815,9 @@ extern FILE *fopen_for_writing(const char *path);
815815
* times, and it must be assignable as an lvalue.
816816
*/
817817
#define FLEX_ALLOC_MEM(x, flexname, buf, len) do { \
818-
(x) = NULL; /* silence -Wuninitialized for offset calculation */ \
819-
(x) = xalloc_flex(sizeof(*(x)), (char *)(&((x)->flexname)) - (char *)(x), (buf), (len)); \
818+
size_t flex_array_len_ = (len); \
819+
(x) = xcalloc(1, st_add3(sizeof(*(x)), flex_array_len_, 1)); \
820+
memcpy((void *)(x)->flexname, (buf), flex_array_len_); \
820821
} while (0)
821822
#define FLEXPTR_ALLOC_MEM(x, ptrname, buf, len) do { \
822823
(x) = xalloc_flex(sizeof(*(x)), sizeof(*(x)), (buf), (len)); \

0 commit comments

Comments
 (0)