Assertion failed: fr->magic == FLI_MAGIC

It could be that some memory is getting corrupted.

Try running with swipl -d chk_secure which will enable some extra debugging/checks to see if you are corrupting a termref or something earlier in your code.

See this post:

This page has more info also:

http://www.swi-prolog.org/pldoc/man?section=foreign-debug