sbrk(0)和sbrk(size)都返回相同的地址

Ang*_*gus 2 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);
}
Run Code Online (Sandbox Code Playgroud)

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).

Som*_*ude 9

当您使用时,您将sbrk(0)获得当前的 "中断"地址.

当您使用时,您将sbrk(size)获得之前的 "中断"地址,即更改前的地址.

因此,如果您调用一次大小为零,然后调用具有正大小的调用,则两者都将返回相同的值.如果使用正尺寸调用再次调用零尺寸,它将返回地址.

  • 你好,能解释一下中断地址是什么吗? (2认同)