I can’t see anything wrong with the code you’ve posted but having the symptoms occur a bit “randomly” depending on context is pretty standard if you’ve got memory corruption going on.
One simple thing you could try for debugging is over-allocating your input arrays and see whether (a) this stops the segfaults and (b) which parts of those arrays are written to unexpectedly.