Fixed a few mem leaks, and C++ compatibility