C
Clint Olsen
I did a Google about this, and I've seen this covered quite a few times -
some leading to useful tricks with offsetof() to discern alignment and
others using a big-union of intrinsic types to discern what the compiler
would do with this kind of data and act accordingly. Others claimed it
couldn't be done or it wasn't worth it.
Rather than dive into the how, I wanted to discuss more of the _why_ since
that was asked a few times and nobody replied to that question.
The best examples I can give are keeping related data together and avoiding
fragmentation by multiple (perhaps unecessary) malloc calls. When writing
ADT libraries, it would be nice to keep node/link info together with the
associated data. The alternative is to force the user to include a
node/link struct in their data structure and force the library writer to
expose his API unecessarily. Another situation is to be able to write a
debugging memory allocator where you have extra space at the beginning of
the allocation section to store information such as file/line info of where
it occurred. Richard's MemTrack library had an example of this in 'C
Unleashed'. Then the info is just a known offset away from the user
pointer. Otherwise you would need a rather complex translation scheme to
tie the addresses to the alloc info since pointer values themselves cannot
be portably used.
I'm just curious as to what others think of this technique and if it's
really worth the effort.
-Clint
some leading to useful tricks with offsetof() to discern alignment and
others using a big-union of intrinsic types to discern what the compiler
would do with this kind of data and act accordingly. Others claimed it
couldn't be done or it wasn't worth it.
Rather than dive into the how, I wanted to discuss more of the _why_ since
that was asked a few times and nobody replied to that question.
The best examples I can give are keeping related data together and avoiding
fragmentation by multiple (perhaps unecessary) malloc calls. When writing
ADT libraries, it would be nice to keep node/link info together with the
associated data. The alternative is to force the user to include a
node/link struct in their data structure and force the library writer to
expose his API unecessarily. Another situation is to be able to write a
debugging memory allocator where you have extra space at the beginning of
the allocation section to store information such as file/line info of where
it occurred. Richard's MemTrack library had an example of this in 'C
Unleashed'. Then the info is just a known offset away from the user
pointer. Otherwise you would need a rather complex translation scheme to
tie the addresses to the alloc info since pointer values themselves cannot
be portably used.
I'm just curious as to what others think of this technique and if it's
really worth the effort.
-Clint