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.
swipl -d chk_secure
See this post:
This page has more info also: