Your method of setting the RESULT looks wrong.
You are using an inner object to directly set the output, that inner object will be invalid when you free B2.
Also, you are setting the length of results after instead of before.
Maybe you should be setting the length of the RESULT and then copy the contents not assigned, therefor, when you free everything, the output will have a copy of it not an image of it which is just a pointer that is now undefined.