Dimitri Danilov
Dimitri Danilov

Reputation: 1352

How these two adresses can be different ?

I have a stucture

typedef struct    s_block
{
  size_t          size;
  struct s_block  *next;
  struct s_block  *back;
  int             free;
  void            *data;
}                 t_block;

And I initialise it this way:

int       createHeader()
{
    void  *data;
    data = sbrk(BLOCK_SIZE + (sizeof(t_block) * 2));
    header = data;
    header->next = header;
    header->back = header;
    header->size = 0;
    createNewBlock(data + sizeof(t_block), BLOCK_SIZE + sizeof(t_block), 0);
    return 0;
}

void  *createNewBlock(void *beginAddress, size_t size, int free)
{
  printf("%d\n", size);
  t_block *newBlock;
  printf("first %p\n", beginAddress);
  printf("addr : %p\n", beginAddress + size);
  newBlock = beginAddress;
  newBlock->back = header->back;
  newBlock->next = header;
  newBlock->size = size;
  newBlock->free = free;
  newBlock->data = beginAddress + sizeof(t_block);
  header->back->next = newBlock;
  header->back = newBlock;
  header->size++;
  show_alloc_mem();
  return newBlock->data;
}

When I display beginAddress in createNewBlock , the address given is good, and when I display the adress of beginAddress + size, it gives me the right adress :

140
first 0x18f9028
addr : 0x18f90b4

But when I enter in my function show_alloc_mem()

void show_alloc_mem()
{
  t_block *tmp;

  tmp = header->next;
  printf("break : %p\n", header);
  while (tmp != header)
  {
    if (tmp->free == 1)
      printf("%p - %p : %d bytes\n", tmp, tmp + tmp->size, (int)tmp->size);
    else
      printf("free: %p - %p : %d bytes\n", tmp, tmp + tmp->size, (int)tmp->size);
    tmp = tmp->next;
  }
}

Strange behaviour happens. The header adress and tmp adresses are correct. But the address of tmp + size isn't.

break : 0x18f9000
free: 0x18f9028 - 0x18fa608 : 140 bytes

Have you got an idea why ?

Upvotes: 1

Views: 85

Answers (2)

Jean-Baptiste Yunès
Jean-Baptiste Yunès

Reputation: 36391

You use two different pointer arithmetic:

  • one with void *
  • one with t_block *

Your compiler permits you to do arithmetic on void * but it is excluded from the standard. Some compilers (yours) use natural arithmetic on void *, so in the first expression it calculates BaseAdressValue+size while in the second BaseAddressValue+40*size (40 is the size of your structure, five 8-bytes pointers, you are on a 64 bits pointer platform).

Upvotes: 2

antiduh
antiduh

Reputation: 12417

You're performing pointer arithmetic, expecting it to behave like integer arithmetic.

The expression tmp + tmp->size evaluates to (int)tmp + sizeof(t_block)*( (int)tmp->size ) because you're adding an integer (tmp->size) to a pointer to a structure (tmp is of type t_block*).

Upvotes: 3

Related Questions