Analysis and understanding of what this code does.

Lurker for a long time, first time poster. I am a student and do not touch the programming course in two years. Now that I'm taking courses again, it's hard for me to read and understand other people's code. I have sample code from the HMC containing part of a simple memory allocator in C.

void free_block(ptr p) {
     *p = *p & ~1;                         /* clear allocated flag */    
     next = (unsigned*)((char*)p + *p);    /* find next blk */   
     if ((*next & 1) == 0)                 /* if not allocated... */     
     *p += *next;                          /*   add to this block */
      }

Despite the comments, I am still embarrassed about what is happening here. I know what the code does, but I could never have encoded it myself. If someone could explain the matte parts of this code, I would be extremely grateful.

+4
source share
2 answers

- , , . .

~ 1 1, 0x01, 0xFE

 *p = *p & ~1;                         /* clear allocated flag */

 0xFFFFFFFE 
(1111 1111 1111 1111 1111 1111 1111 1110)

. .

, p - 0xFFFFFFFE, , (, 1, ).

 next = (unsigned*)((char*)p + *p);    /* find next blk */   

'next' - , p + [ ]

 if ((*next & 1) == 0)                 /* if not allocated... */     
    *p += *next;                          /*   add to this block */

'next' ( AND), 'p' 'next' 'p'.

, , , , ( ).

. , .

+1

, .

*p = *p & ~1;                         /* clear allocated flag */

~ . , ~1 - 1 , , .

, ... .

next = (unsigned*)((char*)p + *p);    /* find next blk */

p char ((char*)p), , p. unsigned int. , p .

, , , , , ...

if ((*next & 1) == 0)                 /* if not allocated... */

, . , , .

    *p += *next;                      /*   add to this block */

p , .

, next, , - . , , , p .

, .

+1

Source: https://habr.com/ru/post/1536127/


All Articles