Sujet : Re: "array"
De : chris.m.thomasson.1 (at) *nospam* gmail.com (Chris M. Thomasson)
Groupes : comp.lang.cDate : 03. Apr 2025, 06:06:50
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <vsl51b$3pr14$1@dont-email.me>
References : 1 2
User-Agent : Mozilla Thunderbird
On 4/2/2025 6:31 PM, Keith Thompson wrote:
ram@zedat.fu-berlin.de (Stefan Ram) writes:
Below, an array is allocated dynamically.
>
#include <stdio.h>
#include <stdlib.h>
>
int main( void )
{ char *array_pointer = malloc( 10 * sizeof *array_pointer );
if( !array_pointer )return EXIT_FAILURE;
*array_pointer = 'a';
free( array_pointer ); }
>
But is it really an array according to the C spec?
Yes.
This is specfied by the standard in the section describing memory
allocation functions. In C17, it's in 7.22.3 paragraph 1 (which applies
to all of aligned_alloc, calloc, malloc, and realloc):
The pointer returned if the allocation succeeds is suitably aligned
so that it may be assigned to a pointer to any type of object with a
fundamental alignment requirement and then used to access such an
object or an array of such objects in the space allocated (until the
space is explicitly deallocated).
The *effective type* rules are also relevant (section 6.5). My reading
of that section is that if you access malloc'ed memory as an array, that
memory has the array type as its effective type.
Iirc, aligned_alloc can only be used with types that are compatible with the alignment. To use it with any object it must be a multiple of max_align_t. What did I miss? Thanks.