Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sbrk(0) and sbrk(size) both return the same address

Tags:

c

#include<unistd.h>
#include<stdio.h>

void *my_malloc(size_t size){
 void *p;
 void *q;
 p = sbrk(0);
 /* If sbrk fails, we return NULL */
 q = sbrk(size);
 if(q == (void *)-1){
  return NULL;
 }
 printf("\n size : %d  p : 0x%x q : 0x%x \n",size,p,q);
 return p;
}
int main(){
 int *p;
 p = my_malloc(5);
 printf("\n p : 0x%x \n",p);
}

brk(2) place the break at the given adress addr and return 0 if successful, -1 otherwise. The global errno symbol indicate the nature of the error. sbrk(2) move the break by the given increment (in bytes.) Depending on system implementation, it returns the previous or the new break adress. On failure, it returns (void *)-1 and set errno. On some system sbrk accepts negative values (in order to free some mapped memory.) Since sbrk’s specification does not fix the meaning of its result, we won’t use the returned value when moving the break. But, we can use a special case of sbrk: when increment is nul (i.e. sbrk(0)), the returned value is the actual break adress (the previous and the new break adresses are the same.) sbrk is thus used to retrieve the begining of the heap which is the initial position of the break. So using sbrk as main tool to implement malloc.

sbrk(0) as well as sbrk(size) both return the same address, what i was expecting is that the sbrk(size) should return the address of 5 bytes ahead from the sbrk(0).

like image 742
Angus Avatar asked Dec 09 '22 16:12

Angus


1 Answers

When you use sbrk(0) you get the current "break" address.

When you use sbrk(size) you get the previous "break" address, i.e. the one before the change.

So if you call it once with a size of zero followed by a call with a positive size, then both will return the same value. If you call it again with a zero size after the call with positive size, it will return the new address.

like image 113
Some programmer dude Avatar answered Dec 20 '22 14:12

Some programmer dude