0

In an implementation of a basic pool i have something like this(i'll simplify the code to be clearer)

struct unit_header{
  struct unit_header* next, prev;
};
int number_of_units = 10
int unit_size = 5;
int full_block = number_of_units*(unit_size+sizeof(struct unit_header));

void* p_mem_full_block = malloc(full_block);

//iterate all units of mem_full_block
for (int i = 0; i< number_of_units; i++){
  //pointer to each unit
  struct unit_header* p_units = (struct unit_header*)((char*)p_mem_full_block + i*(unit_size+sizeof(struct unit_header)));
  //.... some pointers stuff....
}

I do know that this part(below) is used to go through all units of mem_block...

i * (unit_size+sizeof(struct unit_header))

I did not get what this part:

(char*)p_mem_full_block

means. Why do I have to make this char* conversion?

aracyla
  • 58
  • 8
  • Its probably because pointer arithmetic to a `void` pointer is illegal and you are trying to add some value to that pointer. see [this](http://stackoverflow.com/questions/3523145/pointer-arithmetic-for-void-pointer-in-c) – Biruk Abebe May 21 '16 at 06:22

1 Answers1

1

It is because according to C standard you cannot add, subtract anything to void *; however addition and subtraction are defined for char * where they advance the pointer by given number of bytes.

However, GCC allows void pointer arithmetic as an extension without warnings, unless enabled by -Wpointer-arith or -Wpedantic, or so.


Additionally, the whole operation does not look very portable in that the unit_header structure might have alignment requirements that are different from multiples of unit_size. Indeed, the unit_size of 5 will lead to problems, and on many processors such code would compile but crash at runtime because a pointer (prev, next) is misaligned, e.g. the implementation might require an address divisible by 4 or 8, while the code will allow any number in between. However, x86 itself usually does not care about wrong alignment much.

I.e. conversion between two pointer types produces a result that is incorrectly aligned has undefined behaviour as per C11.