Bz/fix freebsd

Fix issues. Tested with freeBSD 9.2 and 10.
And we free it only if there is no error.