-   Programming (
-   -   GTK newbie (

Netooo 03-30-2011 12:25 AM

GTK newbie
Hi, I hope somebody can help me, my program crashes if I uncomment the line "gtk_label_set_text(label,buf);" from the "timer" function. Application works fine to me, I just want a very simple cronometer, and it works if I keep that line commented, the problem is that I can only show the cronometer to the console, and I want it in the GUI.

I don't know why the gtk_label_set_text function works in my function "arranca" but crashes in function "timer", any ideas?


#include <gtk/gtk.h>
#include <time.h>
#include <stdio.h>

gint count = 0;
char buf[8];

void timer(GtkWidget *widget, gpointer label){
 clock_t comienzo;

  sprintf(buf,"%.2f",(clock()-comienzo)/(double)CLOCKS_PER_SEC );

void arranca(GtkWidget *widget, gpointer label){
  else count=0;
  GThread *thread;
    thread=g_thread_create((GThreadFunc)timer, label, FALSE, NULL);

int main(int argc, char** argv) {
  clock_t comienzo;
  int test;

  GtkWidget *label;
  GtkWidget *window;
  GtkWidget *frame;
  GtkWidget *button;
  gtk_init(&argc, &argv);

  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
  gtk_window_set_default_size(GTK_WINDOW(window), 250, 150);
  gtk_window_set_title(GTK_WINDOW(window), "CRONOMETRO");

  frame = gtk_fixed_new();
  gtk_container_add(GTK_CONTAINER(window), frame);

  button = gtk_button_new_with_label("START/STOP");
  gtk_widget_set_size_request(button, 90, 35);
  gtk_fixed_put(GTK_FIXED(frame), button, 50, 50);

  label = gtk_label_new("Alto");
  gtk_fixed_put(GTK_FIXED(frame), label, 180, 60);

  g_signal_connect(window, "destroy",
      G_CALLBACK (gtk_main_quit), NULL);
  g_signal_connect(button, "clicked",
      G_CALLBACK(arranca), label);


  return 0;

paulsm4 03-30-2011 01:42 AM

Two suggestions:

1. Make "buf[8]" larger (maybe you're overwriting your buffer and corrupting adjacent memory).

2. Compile with "-g" and step through the code in under the debugger.
Verify that the hex address of "label" is the same in each of "timer()", "arranca()" and "main()".

'Hope that helps .. PSM

dugan 03-30-2011 08:27 AM


Originally Posted by paulsm4 (Post 4308187)
1. Make "buf[8]" larger (maybe you're overwriting your buffer and corrupting adjacent memory).

And use something other than sprintf, which makes it very easy to make this kind of mistake. Use snprintf, or better yet, change the char arrar to a gchar array and use g-snprintf

All times are GMT -5. The time now is 08:44 AM.