Segmentation fault in sbrk(size_t)
-
13-06-2021 - |
Question
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!
Solution
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
.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow