A memory leak happens when a program allocates memory but does not free it when it is done using it. In the example above, super_size() allocates 100 bytes via calloc() every time it is called, but it neither calls free() on the pointer nor returns the pointer to the calling code. A program that calls this code repeatedly and runs long enough will eventually run out of memory.
Prevent memory leaks by being aware of which piece of code owns a pointer and making sure it gets freed once it is no longer used.
I have 2 questions:
1- why does "memory leak" happen?
2- how to prevent it?
This comment is hidden because it contains spoiler information about the solution
I love this! Not only is is O(n) whereas most of the other solutions are O(n^2), it's 33% faster than my own O(n) solution. I probably never would have thought of doing it this way.
as said by David Vandevoorde on Quora:
"it is available in GCC, Clang, and EDG."
For clarity I link the full answer: https://www.quora.com/What-is-__builtin_popcount-in-c++
I hope I was helpful :)
That's a great solution! Seems I'm not the only one that used .fract(). :-)
Just wanted to say thanks for making this kata. It took me a couple of guesses to get the type syntax for the function table correct. I've been using C for 25 years, and today I learned something new about the language. Thanks! :)
The user is 7kyu. That they solved the problem correctly with such readable code is impressive. Give them a break :)
The allocated buffer doesn't have space for the terminating null char when the input has only letters.
This is why I love codewars! I never would have found about about this.
Does this only work with GNU compilers?
This code reads from numbers without first checking if numbersCount > 0. If numbers is NULL or points to a zero-length allocation, then this read is invalid and could cause a crash.
I think it's what you would write before Rust 1.16+. See this post on Stack Overflow.
sprintf() returns the number of characters written to the string. You could rewrite this:
sprintf(dst, "%d", *str++);
for(;*dst != 0; ++dst);
dst += sprintf(dst, "%d", *str++);
Indeed, thank you for pointing this out.
Memory leak. It doesn't free(s).