|
From: | Paul Eggert |
Subject: | Re: [PATCH] flexmember: update comment |
Date: | Fri, 24 May 2019 15:46:29 -0700 |
User-agent: | Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Thunderbird/60.7.0 |
On 5/24/19 3:17 PM, Bruno Haible wrote:
1) What is the alignment problem if the array element type is 'char'?
Suppose we have a platform where the alignment of each basic type is equal to its size, where sizeof (int) == 4 and sizeof (char) == 1, and where we have 'struct s { int n; char d[]; };' and suppose we want to allocate a 'struct s' with a 3-element flexible array member 'd'. Then 'offsetof (struct s, d) + 3 * sizeof (char)' is 7, and when we call 'malloc (7)' malloc is entitled to assume that memory is being allocated for an array of 7 one-byte objects, so it can return an address that is not a multiple of 4, which means that the pointer that malloc returns is invalid for 'struct s *'. To fix the problem, we can use 'malloc (FLEXSIZEOF (struct s, d, 3))' instead, as FLEXSIZEOF yields 8 on this platform, and malloc (8) must return an address that is a multiple of 4.
No, because if malloc is given an argument like 8 that is a multiple of sizeof (int), it must return a pointer suitable for 'int *'.don't we need to apply a 'ceil'-like alignment to the malloc result?
Perhaps I should update the comment to make this all clearer, though it is hard to be clear and accurate and terse in this area.
[Prev in Thread] | Current Thread | [Next in Thread] |