Re: Book-keeping metadata for allocated memory
- From: Ben C <spamspam@xxxxxxxxx>
- Date: 15 Mar 2006 19:46:26 GMT
On 2006-03-15, David Resnick <lndresnick@xxxxxxxxx> wrote:
pinkfloydhomer@xxxxxxxxx wrote:
I was considering something along the lines of allocating the memory
for Container and thingy in one go, like:
Container* container = malloc(sizeof(Container) + size);
and then return something like
return (container + sizeof(Container));
But is that portable and well-defined? Or are there other solutions?
/David
A pointer returned by malloc is properly aligned for any use. But you
are returning an offset into the malloc'd block. I'm not sure how
you could guarantee that the offset is correctly aligned for your
needs, unless, as I read it, the things being allocated are always
structures. The standard says in section 6.2.5#25 "All pointers to
structure types shall have the same representation and alignment
requirements as each other.". I gather that means that offsetting
into a malloced block by the size of a structure will result in
pointer to memory correctly aligned for that structure, and hence for
other structures? If I'm wrong here, I'll no doubt be swiftly
corrected :)
It does sound a bit surprising. I tried this:
struct thing
{
char c;
};
int main(int argc, char **argv)
{
struct thing *t = malloc(100 * sizeof (struct thing));
printf("%p, %p, %d, %d\n", t, t+1, t+1 - t, sizeof (struct thing));
return 0;
}
and it printed out: 0x804a008, 0x804a009, 1, 1
So t+1 is not aligned on my system.
But there are various ways to guarantee the alignment for a particular
struct, as I suggested in an earlier post.
If the offset pointer needs to have the same alignment as a pointer
originally returned from malloc (i.e. maximum you ever might need), you
have to know what that is.
Practically speaking you probably just define a macro for it, but that's
not ideal, I wonder if there is a better way of determining your maximum
required alignment?
.
- Follow-Ups:
- Re: Book-keeping metadata for allocated memory
- From: Chris Torek
- Re: Book-keeping metadata for allocated memory
- References:
- Book-keeping metadata for allocated memory
- From: pinkfloydhomer@xxxxxxxxx
- Re: Book-keeping metadata for allocated memory
- From: David Resnick
- Book-keeping metadata for allocated memory
- Prev by Date: how to count rows and columns of integers/doubles in a file?
- Next by Date: Re: removing a loop cause it to go at half the speed?
- Previous by thread: Re: Book-keeping metadata for allocated memory
- Next by thread: Re: Book-keeping metadata for allocated memory
- Index(es):
Relevant Pages
|