Tim Rentsch
6/19/2011 9:59:00 PM
jameskuyper <jameskuyper@gmail.com> writes:
> On Tuesday, June 14, 2011 6:00:21 PM UTC-4, Tim Rentsch wrote:
>> James Kuyper <james...@verizon.net> writes:
>>
>> > On 06/10/2011 02:30 PM, ImpalerCore wrote:
> ...
>> >> #define PTR_HEADER_SIZE (sizeof (int))
>> >>
>> >> void* rc_malloc( size_t size )
>> >> {
>> >> void* mem = NULL;
>> >> void* p = NULL;
>> >>
>> >> p = malloc( size + PTR_HEADER_SIZE );
>> >>
>> >> if ( p )
>> >> {
>> >> /* Set the reference count to 1. */
>> >> *((int*)p) = 1;
>> >>
>> >> mem = (unsigned char*)p + PTR_HEADER_SIZE;
>> >> }
>> >>
>> >> return mem;
>> >> }
>> >
>> > The value stored in 'p' is guaranteed to be correctly aligned for all
>> > types. However, the only thing portably guaranteed about alignment off
>> > the value stored in 'mem' is that it is suitable for 'int', it need not
>> > be suitably aligned for any type with a size greater than 1 that is
>> > different from that of 'int'. [snip]
>>
>> Unless one considers the type 'unsigned int' to be a type
>> different from that of 'int'.
>
> I was talking about types "with a size ... that is different from that
> of 'int'". 'unsigned int' is a type with a size that is guaranteed to
> be the same as that of 'int', so that type is just as safe as 'int'
> itself.
I see - the unspecified referent of the final "that" allowed
the earlier statement to be read ambiguously.
But the assertion about size isn't right either. The pointer
value in 'mem' is suitably aligned for any type whose size
evenly divides 'sizeof (int)', or for that matter any type
whose alignment evenly divides 'sizeof (int)'. The second
condition is conservatively testable (no false positives,
only potentially false negatives), and the first is exactly
testable, using completely portable code.