Code fixes

Various code fixes, mostly discovered by MSVC code static analyzer .
Can throw exception.
But it's bad idea to write to pointer memory.