Any time you need to calculate field gradients you need to ensure that the field buffers are up to date. This is done through the variable buffers_up_to_date. If you write a function that changes the values of the fields you should set buffers_up_to_date to zero. This includes any function that Fourier transforms the fields because the Fourier Transform routines can overwrite the parts of the arrays used for the buffers.
If you write a function that requires the buffers - typically because it calculates spatial derivatives - you should check if they are up to date and call the function update_buffers() if they are not. Note, however, that if you are calling the LATTICEEASY function gradient_energy() you don't need to do this check because it's performed inside that function.