Re: Still confused on new thread starting idle functions to update UI.



ok, I may be getting somewhere. I did some reading on heap memory versus stack.

Here's a vastly simplified example program which doesn't use GTK+, but I'm using to demonstrate my plan of 
attack.

I use a function called packit() which allows me to still use strdup().

Comments?

Dave


Valgrind is happy with this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

typedef struct _msgdata msgdatas;
struct _msgdata {
  char *message;
  int *textview;
};

msgdatas *packit (msgdatas *, char *);
int myfunc (msgdatas *);

int
main (int argc, char ** argv)
{
  int i;
  char *message;
  msgdatas *msgdata;

  // Allocate memory on the heap, not stack.
  msgdata = (msgdatas *) malloc (1 * sizeof (msgdatas));
  msgdata->textview = (int *) malloc (1 * sizeof (int));
  message = (char *) malloc (1024);

  // Main loop.
  for (i=0; i<100; i++) {
    sprintf (message, "%i Dave is here.", i);  // In reality, this is a more complicated sprintf().

    *(msgdata->textview) = 7;  // This is a stand-in for a pointer to a textview.
    myfunc (packit (msgdata, strdup (message)));  // strdup() allocates memory for message on the heap.

    sprintf (message, "%i Dave is no longer here.", i);  // In reality, this is a more complicated sprintf().

    *(msgdata->textview) = 3;  // This is a stand-in for a pointer to a textview; only changed for fun.
    myfunc (packit (msgdata, strdup (message)));  // strdup() allocates memory for message on the heap.
  }

  // Don't free msgdata->message; it gets free'd by myfunc().
  free (msgdata->textview);
  free (msgdata);
  free (message);

  return (EXIT_SUCCESS);
}

msgdatas *
packit (msgdatas *msgdata, char *message)
{
  msgdata->message = message;

  return (msgdata);
}

// This is a stand-in for an idle function which would update the textview in the UI.
int  // Would really be gboolean
myfunc (msgdatas *data)
{
  printf ("Pointer to textview: %i\n", *(data->textview));
  printf ("message: %s\n", data->message);

  // Only free the element "message" of msgdatas struct.
  free (data->message);

  return (EXIT_SUCCESS);  // Would really be return (G_SOURCE_REMOVE)
}


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