0

My program is very simple,

...
#define TO_INT(a) (*(int *)a)
void *pool_head;
void *pool_tail;
...

pool_head = sbrk(BUF_LENGTH);
if (pool_head == (void *)-1) {
    errno = ENOMEM;
    return pool_head;
}
pool_tail = sbrk(0);
TO_INT(pool_head)     = BUF_LENGTH * -1;
TO_INT((pool_tail - 3)) = BUF_LENGTH * -1;

When I debug it, It show:

Program received signal SIGSEGV, Segmentation fault. at TO_INT((pool_tail - 3)) = BUF_LENGTH * -1;

the value of pool_tail & pool_head:

pool_tail = 0x805a000

pool_head = 0x804a000

How to solve it? Thank you!

thlgood
  • 1,275
  • 3
  • 18
  • 36

1 Answers1

2

First, you cannot perform pointer arithmetic (pool_tail - 3) on void *.

Second, even if we allow it and treat pool_tail as char *, subtracting pool_tail by 3 does not give enough room to fit an int.

univerio
  • 19,548
  • 3
  • 66
  • 68
  • Cast it to `char *` first. Alternatively, you can simply do `*((int *)pool_tail - 1) = BUF_LENGTH * -1`. This will move `pool_tail` down by `sizeof(int)` (which is exactly 4) and thus ensure you have exactly enough room for one `int`. – univerio Jun 08 '12 at 01:44
  • @thlgood That's great! Keep in mind that you should mark an answer as the solution if it indeed solved your problem. – univerio Jun 08 '12 at 01:57