DMCKITT
DMCKITT

Reputation: 45

gtk_widget_destroy on GtkFileChooserDialog results in segmentation fault

I have a problem with my first GTK+ Application. I tried to implement saving to an XML File. It works like it should but sometimes, the program crashes at gtk_widget_destroy(save_dialog) with a segmentation fault. I really have no clue why this is happening.

I hope someone can may help me.

Code of the function:

static void save_file_from_source_view(gboolean is_save_as)
{
  GtkTextIter start, end;
  char *text_content;

  gtk_text_buffer_get_start_iter(GTK_TEXT_BUFFER(text_editor_buffer), &start);
  gtk_text_buffer_get_end_iter(GTK_TEXT_BUFFER(text_editor_buffer), &end);
  text_content = gtk_text_buffer_get_text(GTK_TEXT_BUFFER(text_editor_buffer), &start, &end, FALSE);

  if(is_save_as||last_filename==NULL)
  {
    GtkWidget *save_dialog;
    gint result;

    save_dialog = gtk_file_chooser_dialog_new("Save File", GTK_WINDOW(window), GTK_FILE_CHOOSER_ACTION_SAVE, "Cancel", GTK_RESPONSE_CANCEL, "Save", GTK_RESPONSE_ACCEPT, NULL);
    gtk_file_chooser_set_do_overwrite_confirmation(GTK_FILE_CHOOSER(save_dialog), TRUE);
    gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(save_dialog), last_filename!=NULL? last_filename:"untitled.xml");
    result = gtk_dialog_run(GTK_DIALOG(save_dialog));
    if(result == GTK_RESPONSE_ACCEPT)
    {
      char *filename;
      filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(save_dialog));
      save_file(filename, text_content);
      g_free(last_filename);
      last_filename = malloc(sizeof(filename));
      g_print("Got here 1\n");
      strcpy(last_filename, filename);
      g_print("Got here 2\n");
      g_free(filename);
      g_print("Got here 3\n");
    }
    g_print("Got here 4\n");
    gtk_widget_destroy(save_dialog); // Crashes here
    g_print("Got here 5\n");
  }
  else
  {
    save_file(last_filename, text_content);
  }
}

Output:

Got here 1
Got here 2
Got here 3
Got here 4
Segemntation fault (core dumped)

Upvotes: 1

Views: 227

Answers (1)

David Ranieri
David Ranieri

Reputation: 41017

For sure you want the length of the string:

last_filename = malloc(strlen(filename) + 1);

instead of the size of a pointer to char (as you did):

last_filename = malloc(sizeof(filename));

Don't forget to call free(last_filename) at the end in order to avoid memory leaks.

Upvotes: 1

Related Questions