-
Memory Alignment
hi all,
I have a block of memory, and I am storing arbitrary number of basic types ( floats, ints, chars, and char* ( strings )) in this block of memory.
--------------------------------------
| int | int | float .....
--------------------------------------
When I want to access these variables, I use a pointer to the first byte of this memory block and an index, something like this
eg. to access the second int,
Code:
char* block_pointer = new char[1024];
...
...
// to access the second int
int second_int = *(block_pointer + sizeof(int));
my question is, would this approach produce undesired effects ( alignments problems )
-
If the integers are not aligned on correct alignment boundry, asscess will be slower but the data should still be ok.
-
> my question is, would this approach produce undesired effects ( alignments problems )
Yes.
Maybe not immediately, but long term it is not a good approach.
Here's someone else who's managed to dig a pit for themselves
http://cboard.cprogramming.com/showthread.php?t=79516
-
If you store the values as ints or floats or the correct type no...
//value = int type
*((int*)(block_pointer + sizeof(int))) = int_value;
//Next value = double...
*((double*)(block_pointer + 2*sizeof(int))) = double_value;
//...
int second_int = *((int*)(block_pointer + sizeof(int)));
double third_double = *((double*)(block_pointer + 2*sizeof(int)));
-
> *((double*)(block_pointer + 2*sizeof(int))) = double_value;
How does this solve anything?