2

In my Application I have struct:

struct
{
  gchar *xen_srv_addr;
  gchar *xen_srv_usr;
  gchar *xen_srv_psw;
  gchar *xen_srv_prt;
} Xen_Server_Connection;

I want to assign a values to that gchars. I read it from file, parse with strtok and return as a char*. Setting parser looks for specific tokens and:

if(a==b)
  {
    Xen_Server_Connection.xen_srv_addr=Parm_Pars(pattern, 2);
    .....
  }  

This assignment works only inside this if block. gchar became garbage just after it. But if I:

if(a==b)
  {
    Xen_Server_Connection.xen_srv_addr="192.168.1.1";
    .....
  }

All seems ok and I can access to that gchar globally. Seems I don't understand something

pugnator
  • 665
  • 10
  • 27

1 Answers1

2

You don't understand what lifetime guarantees the Parm_Pars() function gives on the returned value. It seems it doesn't live forever, so you need to duplicate it if you want to hang on to it.

Simply wrap that line in a call to g_strdup() to get a dynamically allocated copy and you should be fine. Of course, when you want to free your Xen_Server_Connection, you must call g_free() on all duplicated strings or you will leak memory.

UPDATE: Mixing plain char and gchar is fine, glib guarantees that gchar is just an alias for char. I think they even recommend (somewhere) that applications never use gchar.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • Oh, such a silly mistake. Thanks a lot! Just one more question. In this case is it good at all to mix char and gchars in one code? – pugnator Aug 23 '12 at 13:48
  • @unwind You read it here on StackOverflow: http://stackoverflow.com/questions/2800310/converting-an-array-of-characters-to-a-const-gchar/2800318#2800318 – ptomato Aug 23 '12 at 15:42