Let's narrow the subject down to the 'C' case.
In case of implementing reusable library, sometimes we want to add some hidden information at the allocated memory used in the library. To achieve this, library may support special paired-interface. For example
void* mylib_malloc(unsigned int size); void mylib_free(void* p);
To simplify discussion, let's assume that we want add just hidden 'int' value.
We can easily think two options.
- add hidden value to the end of allocated memory. -- (*1)
- add to the start of it. -- (*2)
But we cannot use (*1), because, in general, we cannot know size of memory that is allocated. Therefore there is no general way to access hidden value by address.
So, (*2) is only way we can use. Actually, this is general way to implement standard 'malloc' function, too.
then, memory block structure will be like this.
returned value of 'mylib_malloc' | v +------------+------------------- | hidden-int | user-allocated +------------+-------------------
We should keep in mind these.
- Size of hidden value depends on data-align-constraint. That is, memory address of user-allocated-space should obey data-align-constraint. For example, in case of 32bit ARM, 4 byte data align is required. So, size of hidden value should be multiple of 4 to get 4-byte-aligned-address for user space.
- 'mylib_alloc/mylib_free' should make a pair. (Standard-free-function should not be used - it raises error.)
'Language > C&C++' 카테고리의 다른 글
[C/C++] type of hard-coded-string. (0) | 2010.09.16 |
---|---|
[C/C++] Function pointer. (0) | 2010.05.24 |
[C/C++] Mimicking Signal and Slot (0) | 2010.04.08 |
[C/C++] Intereseting compile error of Passing function pointer as an argument of template class member... (0) | 2009.09.28 |
[C/C++] classifing function return value type... (0) | 2009.09.02 |