pointers - C - Can return value of malloc be used array-like (alignment)? -
often malloc used allocate memory n elements of primitive datatype (int, float, char). this:
#define n 10 double *mem = malloc(n * sizeof(double)); (int = 0; < n; ++i) { mem[i] = 10.0; // write double d = mem[i]; // read } this work if declared mem char * , used cast later on:
char *mem = malloc(n * sizeof(double)); (int = 0; < n; ++i) { *(double*)(mem + * sizeof(double)) = 10.0; double d = *(double *)(mem + * sizeof(double)); } currently i'm wondering if defined , working every datatype (even complex type struct). lets assume struct a anything. following defined?
char *mem = malloc(n * sizeof(struct a)); (int = 0; < 10; ++i)) { *(struct *)(mem + * sizeof(struct a)) = /* valid */; struct x = *(struct *)(mem + * sizeof(struct a)); } since return value of malloc suitably aligned kind of variable case i = 0 defined , working, how i = 1, 2, ...? alignment screw up? in example:
char char_arr[4] = /* value */; int *d = &char_arr[0]; the second line not guaranteed work, since char_arr may not aligned on 4-byte boundary (required int).
is following defined?
char *mem = malloc(n * sizeof(struct a)); (int = 0; < n /* 10 */; ++i)) { *(struct *)(mem + * sizeof(struct a)) = /* valid */; // struct = *(struct *)(mem + * sizeof(struct a)); struct x = *(struct *)(mem + * sizeof(struct a)); } almost always.
in terms of alignment, *alloc() returns pointer memory valid fundamental alignments op noted. (struct *)(mem + * sizeof(struct a)) provide aligned pointer 0 <= <= n.
not concern op, yet on rare machines i * sizeof(struct a) overflow size_t math (with large enough i , sizeof(struct a), whereas mem[i] not. not seen on common implementations use flat memory address.
also robust code checks memory allocation failures.
candidate simplified code. notice type ptr points not relevant, assuming not defined void *ptr. @usr.
ptr = malloc(sizeof *ptr * n); if (ptr == null) handle_oom(); (size_t = 0; < n; ++i)) { ptr[i] = /* valid */; } `
Comments
Post a Comment