Newsgroup: comp.lang.c++
Subject: safe "struct hack"?
From: Jonathan Lee <jonathan.lee.975@...>
Date: Wed, 14 Aug 2013 06:45:11 -0700 (PDT)
Hello all,
I've have a variation of the struct hack that I think is legal. Wondering if anyone could spot a reason why not. (By struct hack I mean putting a variable length array at the end of a struct, or a struct at the beginning of an array).
Suppose I want to add an int array to the end of
struct header
{
int a;
int b;
double c;
// int arr[]; // I think C99 would do this
}
Then I can make the union
union wrap
{
header hdr;
int arr[1];
}
And use calloc to get some memory
void* p = calloc(20, sizeof(wrap));
The following casts should be legal:
union* u = static_cast<union*>(p);
header* h = static_cast<header*>(u);
int* i = static_cast<int*>(u);
But, then, this should also be legal
int* j = static_cast<int*>(u + 1);
which is an aligned int pointer just past the header
struct. Seeing as how this came from calloc-d, "void"
memory, I think j + 0, j + 1, j + 2, ... are legal
int addresses.
After all, I can legally use
int* q = static_cast<int*>(p);
as an int array. I don't see why j would be any
different.
Can anyone see why this wouldn't be the case?
Thanks in advance,
--Jonathan
Subject: safe "struct hack"?
From: Jonathan Lee <jonathan.lee.975@...>
Date: Wed, 14 Aug 2013 06:45:11 -0700 (PDT)
Hello all,
I've have a variation of the struct hack that I think is legal. Wondering if anyone could spot a reason why not. (By struct hack I mean putting a variable length array at the end of a struct, or a struct at the beginning of an array).
Suppose I want to add an int array to the end of
struct header
{
int a;
int b;
double c;
// int arr[]; // I think C99 would do this
}
Then I can make the union
union wrap
{
header hdr;
int arr[1];
}
And use calloc to get some memory
void* p = calloc(20, sizeof(wrap));
The following casts should be legal:
union* u = static_cast<union*>(p);
header* h = static_cast<header*>(u);
int* i = static_cast<int*>(u);
But, then, this should also be legal
int* j = static_cast<int*>(u + 1);
which is an aligned int pointer just past the header
struct. Seeing as how this came from calloc-d, "void"
memory, I think j + 0, j + 1, j + 2, ... are legal
int addresses.
After all, I can legally use
int* q = static_cast<int*>(p);
as an int array. I don't see why j would be any
different.
Can anyone see why this wouldn't be the case?
Thanks in advance,
--Jonathan
via Usenet Forums - Usenet Search,Free Usenet - comp.lang.c++ http://www.pocketbinaries.com/usenet-forums/showthread.php?65663-safe-struct-hack&goto=newpost
View all the progranning help forums at:
http://www.pocketbinaries.com/usenet-forums/forumdisplay.php?128-Coding-forums
No comments:
Post a Comment