Fix an invalid memory access.

bi was freed before accessing it.
Fix a potential memory leak.