Skip to content

Comment on Ask HN: Favorite pointer tricks in C?parent

Comments

In fact, a lot of code does this to avoid mallocs. Just be sure to check the length before you put anything into the buffer.

Also, making it a power of 2 is a good idea if you are concerned about alignment.

Just be sure to check the length before you put anything into the buffer.

No need to check. The comment reassures both me and future maintainers that I have countenanced this potential pitfall! Assign away....

Smashing the Stack for Fun and Profit...

Also, making it a power of 2 is a good idea if you are concerned about alignment.

Actually, there are many reasons why this may not be the case. Remember back to when you implemented a user-space memory allocator. One of the most straightforward algorithms is to use power-of-two blocks with varying coalescing algorithms. The problem that you get with your style and this malloc implementation is that, since you need to store memalloc metadata in the block (probably), each block has just slightly less than a power of two space, which means a block request for a power of two will always waste an enormous amount of space by pushing up to the next power of two block size.

Now, this "power of two allocation is best" misconception is so widespread that many memory allocators actually purposefully account for the case where the memory allocation is a power of two and make their block sizes just slightly larger. Just goes to show you what minor things can do to performance.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.