Why not post the function where its actually crashing?
Also the code looks verrry unclean (f.e. 2 times check for key_i or a varibale with no use etc..)