F
Francois Grieu
Hello, I'm asking myself all kind of questions on allocating
an array of struct with proper alignment.
Is the following code oorrect ?
I'm most interested by the statement
t = malloc(n*sizeof(r))
and (to a degree) by the surrounding error checking.
#include <stdlib.h>
// a record of system-dependent size and alignment
typedef struct r
{
char f0;
long f1;
char f2;
} r;
int main(int argc, char *argv[])
{
long n; // number of elements to allocate
r *t; // array of n records of type r
if (argc==2 && // check argv[1] is our single parameter
(n = atol(argv[1]))>0 && // convert to a positive number
(size_t)(n*sizeof(r))/n==sizeof(r) && // check for size overflow
// allocate n records of type r; is that OK ?
(t = malloc(n*sizeof(r)))!=NULL)
{
// some use the array of n records
long j;
for(j=0;j<n;++j)
t[j].f1 = j; // use a (conseivably) aligned field
free(t);
}
return 0;
}
On systems where alignment must occur for proper acess to
the field f1, is sizeof(r) guaranteed to be rounded up
appropriately, and/or malloc guaranteed to return approriately
aligned memory ?
Is the calloc() library function guaranteed to perform something
extra (beside zeroing the allocated memory) ? like, perhaps,
rounding up the size passed, or checking that the product does
not overflow, or making extra alignment ?
As an aside: one of my C compilers barks if I change sizeof(r)
to sizeof r. Is this compiler defective ? No it is NOT C++.
TIA,
Francois Grieu
an array of struct with proper alignment.
Is the following code oorrect ?
I'm most interested by the statement
t = malloc(n*sizeof(r))
and (to a degree) by the surrounding error checking.
#include <stdlib.h>
// a record of system-dependent size and alignment
typedef struct r
{
char f0;
long f1;
char f2;
} r;
int main(int argc, char *argv[])
{
long n; // number of elements to allocate
r *t; // array of n records of type r
if (argc==2 && // check argv[1] is our single parameter
(n = atol(argv[1]))>0 && // convert to a positive number
(size_t)(n*sizeof(r))/n==sizeof(r) && // check for size overflow
// allocate n records of type r; is that OK ?
(t = malloc(n*sizeof(r)))!=NULL)
{
// some use the array of n records
long j;
for(j=0;j<n;++j)
t[j].f1 = j; // use a (conseivably) aligned field
free(t);
}
return 0;
}
On systems where alignment must occur for proper acess to
the field f1, is sizeof(r) guaranteed to be rounded up
appropriately, and/or malloc guaranteed to return approriately
aligned memory ?
Is the calloc() library function guaranteed to perform something
extra (beside zeroing the allocated memory) ? like, perhaps,
rounding up the size passed, or checking that the product does
not overflow, or making extra alignment ?
As an aside: one of my C compilers barks if I change sizeof(r)
to sizeof r. Is this compiler defective ? No it is NOT C++.
TIA,
Francois Grieu