Search code examples
c++iteratorsegmentation-faultgtkgtk3

"gtk_text_buffer_get_bounds" function causes SEGFAULT


I'm writing a GTK application where I need to put a string into a GtkTextBuffer and then later extract the same text back out into a separate string. For some reason, I keep receiving a SEGFAULT error during "gtk_text_buffer_get_bounds" function. I think it's a problem with the "e" iterator, but I'm not sure.

I've isolated the offending operations into a smaller example program. There are no differences between the process below and the one in my application.

What am I doing wrong?

#include <iostream>
#include <gtk/gtk.h>
int main ()
{
  const char *string1 = "hello\0", *string2;
  GtkTextBuffer *text = gtk_text_buffer_new (NULL);
  GtkTextIter *s, *e;

  gtk_text_buffer_set_text (text, string1, -1);
  gtk_text_buffer_get_bounds (text, s, e);
  string2 = gtk_text_buffer_get_text (text, s, e, TRUE);
  std::cout << string2 << std::endl;
  return 0;
}

Solution

  • You're declaring s and e as pointers, and they are getting default-initialized to nullptr, so when gtk_text_buffer_get_bounds and gtk_text_buffer_get_text get around to using them you get a null pointer dereference and a segfault:

    GtkTextIter *s, *e;
    ...
    gtk_text_buffer_get_bounds (text, s, e);
    ...
    string2 = gtk_text_buffer_get_text (text, s, e, TRUE);
    

    Instead, you could just allocate the GtkTextIter objects on the stack and pass their addresses around:

    GtkTextIter s, e;
    ...
    gtk_text_buffer_get_bounds (text, &s, &e);
    ...
    string2 = gtk_text_buffer_get_text (text, &s, &e, TRUE);