How do malloc() and free() work?

后端 未结 13 2481
谎友^
谎友^ 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:54

    Your program crashes because it used memory that does not belong to you. It may be used by someone else or not - if you are lucky you crash, if not the problem may stay hidden for a long time and come back and bite you later.

    As far as malloc/free implementation goes - entire books are devoted to the topic. Basically the allocator would get bigger chunks of memory from the OS and manage them for you. Some of the problems an allocator must address are:

    • How to get new memory
    • How to store it - ( list or other structure, multiple lists for memory chunks of different size, and so on )
    • What to do if the user requests more memory than currently available ( request more memory from OS, join some of the existing blocks, how to join them exactly, ... )
    • What to do when the user frees memory
    • Debug allocators may give you bigger chunk that you requested and fill it some byte pattern, when you free the memory the allocator can check if wrote outside of the block ( which is probably happening in your case) ...

提交回复
热议问题