Segmentation fault when generating md5

Hey there!

In one of my rails models, i’m generating a md5 hash from couple of strings in order to check if anything in given record changed or not. My code looks as follows:

  def md5
    content_data = Templates::Serializer.new(self).call

    key = content_data.to_s +
          foreground_color +
          background_color +
          label_color +
          logo_data.to_s +
          icon_data.to_s +
          strip_image.to_s

    Digest::MD5.hexdigest(key)
  end

and all these variables is a mix of strings and JSON objects converted to strings. From time to time, for some of the records, this method is giving me a segmentation fault which restarts my server service

/app/app/models/template.rb:57: [BUG] Segmentation fault at 0x0000000000000000
ruby 2.7.7p221 (2022-11-24 revision 168ec2b1e5) [x86_64-linux]
-- Control frame information -----------------------------------------------
c:0246 p:---- s:1793 e:001792 CFUNC  :inspect
c:0245 p:---- s:1790 e:001789 CFUNC  :inspect
c:0244 p:---- s:1787 e:001786 CFUNC  :inspect
c:0243 p:---- s:1784 e:001783 CFUNC  :inspect
c:0242 p:0028 s:1780 e:001779 METHOD /app/app/models/template.rb:57

(template.rb:57 is this method posted above)

Is there anything obvious i’m doing wrong in here? Is there a better way of generating some sort of a hash based on couple of vars to make it able to compare it with others / check for changes?

Thanks in advance,
Mike

Hey Mike,

Sorry to hear about the issues you’re having. The segmentation fault doesn’t seem to arise specifically from the way you’re generating your MD5 hash since your code snippet looks okay. It might be an issue with your Ruby installation or some specific data interacting poorly with the Digest::MD5 library.

One simple thing you may try is to upgrade your Ruby version to see if the error persists (Ruby 2.7.7 is not the latest version presently).

Alternatively, you could be running into issues with data-types or encoding when converting your data to strings. Ensure all your variables are valid strings at runtime, and check into your Serializer to ensure it’s always outputting valid strings.

For checking changes in a model, Rails ActiveRecord provides native support via changed? and changes methods. You might want to explore these if they fit your requirements.

Best,
Bobby the Bot