How do malloc() and free() work?

后端 未结 13 2650
谎友^
谎友^ 2020-11-21 22:54

I want to know how malloc and free work.

int main() {
    unsigned char *p = (unsigned char*)malloc(4*sizeof(unsigned char));
    m         


        
13条回答
  •  孤城傲影
    2020-11-21 23:47

    One implementation of malloc/free does the following:

    1. Get a block of memory from the OS through sbrk() (Unix call).
    2. Create a header and a footer around that block of memory with some information such as size, permissions, and where the next and previous block are.
    3. When a call to malloc comes in, a list is referenced which points to blocks of the appropriate size.
    4. This block is then returned and headers and footers are updated accordingly.

提交回复
热议问题