Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save compiler-errors/5f5abd2a73f5615b893077faa835d339 to your computer and use it in GitHub Desktop.
Save compiler-errors/5f5abd2a73f5615b893077faa835d339 to your computer and use it in GitHub Desktop.

So we've got our struct. Imagine augmenting it with a bool called mark:

struct Foo {
  bool mark;
  int data_size;
  char[] data;
}

So we can walk through the pool of Foos that begins at buffer and ends at end:

while (iter < end) {
  Foo *block = (Foo *)iter;
  printf(“Ive got a block of size %d. She is %s. She encodes: %s.”, 
         block->size, block->mark ? "marked" : "not marked", block->data);
  iter += sizeof(struct Foo) + block->size;
}

Imagine I wanted to compact this buffer, removing all the structs which have mark == false...

So compaction basically looks like:

char *from = buffer, *to = buffer;

while (from < end) {
  Foo *block = (Foo *)from;
  size_t size = sizeof(struct Foo) + block->data_size;
  
  if (block->mark) {
    // reset the mark:
    block->mark = false;
    
    // Compact by moving from `from` to `to`.
    memmove(to, from, size);
    to += size;
  } else {
    // Don't do anything, since we're getting rid of this block.
    printf("Freed block of size %d\n", block->data_size);
  }
  
  from += size;
}

end = to;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment