Reputation: 116
How come this works
char p;
p = sbrk(0);
brk(p+1);
*p = 1;
printf("%p %d %p\n",p,*p,sbrk(0));
p++;
*p = 5;
printf("%p %d\n",p,*p);
p++;
*p = 6;
printf("%p %d\n",p,*p);
p++;
*p = 1;
printf("%p %d\n",p,*p);
p++;
*p = 38;
printf("%p %d\n",p,*p);
p++;
*p = 61;
printf("%p %d %p\n",p,*p,sbrk(0));
but when i remove the brk(p+1); it causes a segfault? i also tried removing the first *p = x; before the first p++; i've also tried brk(p-1) and that caused a seg fault. what exactly is going on here? how come i can control all the memory if i just do brk(p+1)? but get a segfault if i don't.
Upvotes: 3
Views: 41
Reputation: 25908
brk()
and sbrk()
allocate memory in page-sized pieces. So brk(p+1)
allocates a whole new page, even though you asked for a single byte. So the few bytes you are writing easily fit within the page you just allocated, and you don't segfault.
Upvotes: 5