Sorting an array causes segfaulting

So, I have a array with an custom structure which I want to sort according to an integer inside it.

However, when I run the sort function, it segfaults when accessing said integer to do the sorting and I do not understand what causes this.

Following is part of the code involved:

using GLib;

// A part of the structure
public struct Backend.TextModule {
  public string text;
  public uint text_start;
}

// A method inside the class utilizing this structure
class Post {
  // The array in question
  private TextModule?[] text_modules;

  private void parse_text {
    // Array is filled in a loop from reading in a JSON file
    json.foreach_element ((array, index, element) => {
      if (element.get_node_type () == OBJECT) {
        Json.Object obj    = element.get_object ();
        Json.Array  length = obj.get_array_member ("indices");
        var entity         = TextModule ();
        entity.text        = obj.get_string_member ("text");
        entity.text_start  = (uint) length.get_int_element (0);
        text_modules += entity;
      }
    });

    // The breaking sort function
    qsort_with_data<TextModule?> (text_modules, text_modules.length, (a, b) => {
      uint x, y;
      x = a.text_start;
      // FIXME: Somewhere here it segfaults...
      y = b.text_start;
      return (int) (x > y) - (int) (x < y);
    });
  }
}

I now have spend around a day trying to find the issue using the limited docs I could find, but to no result.

So, I do hope someone here can help me with my issue.

You are mixing the glib sorting with JSON parsing. The obvious way to debug your issue would be to split these two first: Manually create some verified test data which you then sort. If that works, then the problem is your JSON parsing, and you would have to investigate that. If sorting with verified test data does not work, then you would have to consult Vala glib API docs to see if you use the sorting function in the correct way. And finally, when you think that you use it in the correct way but it fails, then you would have to create C code and call the function from C. If that does not work too, then the glib function may be broken, but that is unlikely. If C code works, then Vala bindings may be broken. In the first case you would have to contact gtk core devs, and in the second case you would have to contact Vala devs or maybe investigate the vala bindings yourself. Well that is some work, but debugging is a core component of computer programming, and you decision using Vala may be not the easiest road.

I can not help you, as I do not really know Vala, and I know only a few of the most basic glib functions.

1 Like