Fixing some memory allocation and corruption issues