Re: [gtk-list] another GDK segfault...



>i've got a little snippet of code that segfaults everytime i call it.
>if this is a stupid error, i'm sorry, i'm still learning C.

[snip]

>gchar
>*thishostname()
>{
>	struct hostent *thishost;
>	sethostent(0);
>	thishost = gethostent() ;
>	endhostent();
>	return thishost->h_name;
>	
>}

I'm not in Unix now so I can't verify things but I'll take an educated guess.

gethostent() is probably returning a pointer to a data structure that is
created by sethostent() and destroyed by endhostent(). The variable
thishost gets the pointer to the temporary data structure. The routine is
returning a pointer to an element of a data structure which no longer
exists. When the printf() tries to access the string based on the pointer
it receives you will get a segfault as the pointer is no longer valid.

Take a close look at the man pages for sethostent(), endhostent(), and
gethostent(). Chances are you need to malloc some memory and then copy the
contents of the memory pointed to by thishost in to the malloc'd area
before calling gethostent().

You will need to malloc the data area outside thishostname() or declare the
variable for the malloc'ed area in thishostname() as static or else you
will still have the same problem (invalid pointer) when you return to the
main routine.

Of course, you should be testing the value returned for validity before
trying to use it. Perhaps gethostent() was returning NULL.



Cheers!

Kevin.  (http://www.interlog.com/~kcozens/)

Internet:kcozens at interlog.com   |"What are we going to do today, Borg?"
      or:ve3syb at rac.ca          |"Same thing we always do, Pinkutus:
Packet:ve3syb@va3bbs.#scon.on.ca.na|  Try to assimilate the world!"
#include <disclaimer/favourite>    |              -Pinkutus & the Borg



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