Re: Segmentation fault in creating basic app using GTK+ (with C)

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi,

As Tadej told, your problem is that you are assign p->one and p->two 
to pointers that aren't initialized.

> GtkWidget *textEntry;
> GtkWidget *label;
> GtkWidget *grid;
> struct mulptr *p = (struct mulptr *)malloc(sizeof(struct mulptr));
> p->one = textEntry; // here
> p->two = label;     // and here, textEntry and label have a 
undefined >                     // value

but, I've some things to add:
 * note that you're allocating(malloc) but not freeing.
 * I recommend create a typedef of your struct to simplify things out.
 * I recommend use of GString over c-strings, quote from doc:

> A GString is an object that handles the memory management of a C > 
string for you.

here is your code with modifications that I've said:

#include <gtk/gtk.h>
#include <string.h>
#include <stdlib.h>


typedef struct
{
  GtkWidget *one;
  GtkWidget *two;
  GString   *str;
} mulptr;

int tofarenheit(int c)
{
  return (c*1.8 + 32);
}

void calculate(GtkWidget *widget, gpointer data)
{
  mulptr *p = (mulptr *) data;
  int res = 0, F;

  res = atoi(gtk_entry_get_text(GTK_ENTRY(p->one)));
  if(res)
  {
    F = tofarenheit(res);
    g_string_printf (p->str, "%d", F);
  }
  else
    g_string_overwrite (p->str, 0, "Invalid Input!");
  gtk_label_set_text(GTK_LABEL(p->two), p->str->str);
}

int main(int argc, char *argv[])
{
  // Decleration
  GtkWidget *window;
  GtkWidget *calButton;
  GtkWidget *grid;
  mulptr p;

  // Initilization
  gtk_init(&argc, &argv);

  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  //gtk_window_set_default_size(GTK_WINDOW(window), 480, 320);
  gtk_window_set_title(GTK_WINDOW(window), "Celcius to Ferenheit 
Converter");
  gtk_container_set_border_width(GTK_CONTAINER(window), 10);
  grid = gtk_grid_new();

  p.str = g_string_new ("Result here");
  p.two = gtk_label_new(p.str->str);
  p.one = gtk_entry_new();
  calButton = gtk_button_new_with_label("Calculate");

  // Adding widget to frame
  gtk_container_add(GTK_CONTAINER(window), grid);
  gtk_grid_attach(GTK_GRID(grid), p.one, 0, 0, 1, 1);
  gtk_grid_attach(GTK_GRID(grid), p.two, 1, 0, 1, 1);
  gtk_grid_attach(GTK_GRID(grid), calButton, 0, 1, 1, 1);


  // Signal Handlers
  g_signal_connect (window, "delete-event", G_CALLBACK 
(gtk_main_quit), NULL);
  g_signal_connect (calButton, "clicked", G_CALLBACK(calculate), &p);


  // Essentials
  gtk_widget_show_all(window);
  gtk_main();
  
  // Free
  g_string_free (p.str, TRUE);

  return 0;
}

_______________________________________________
gtk-list mailing list
gtk-list@xxxxxxxxx
https://mail.gnome.org/mailman/listinfo/gtk-list




[Index of Archives]     [Touch Screen Library]     [GIMP Users]     [Gnome]     [KDE]     [Yosemite News]     [Steve's Art]

  Powered by Linux