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
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 yourXen_Server_Connection, you must callg_free()on all duplicated strings or you will leak memory.UPDATE: Mixing plain
charandgcharis fine, glib guarantees thatgcharis just an alias forchar. I think they even recommend (somewhere) that applications never usegchar.