Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Memory leak concern

Status
Not open for further replies.

chigley

Programmer
Sep 30, 2002
104
GB
I am writing a function to wrap the winsock2.h function gethostname. I am concerned I have introduced a memory leak by using malloc, as if I put a free() after the return statement it will not fire. Can someone guide me?

Code:
char * getLocalHostName(){
     char * hostName = (char *)malloc(256);
     int nameLen = 256; 
     if (gethostname(hostName,nameLen)>0){
        return "Error retrieving local host name";
     }    
     else{
          return hostName;
          free(hostName);
     }
}

Charlie Benger-Stevenson
Hart Hill IT Ltd
 
As long as the function that calls getLocalHostName() remembers to free() the returned pointer, there is no leak. However, since you return malloc'ed memory in one place and a constant literal string in another, the caller cannot safely free() the pointer because freeing a constant literal string is undefined behavior and will most likely blow up.

A better implementation would be:
Code:
int getLocalHostName( char*  buf, int bufSize )
{
   return gethostname( buf, bufSize );
}
But of course in this case, what's the point in just wrapping gethostname() in an extra function call?

So the question comes down to: what exactly are you trying to do with your custom function that can't be done with gethostname() by itself?
 
Well, partly I am trying to resurrect my C programming skills so I can write a Kernel mode driver that does some low level network monitoring using the Windows Filter Driver.

I need to be able to do stuff like

enumerate NICs
Get network information about the host system
Get network information about wireless interfaces

I notice that some of this stuff lives in winsock2.h, some in iputils etc etc so I thought I could write some wrapper functions so everything could be in one logical unit.

In this case I have simplified the call to gethostname, but this is only one part of the function I was writing, when I got spooked about memory leaks. The rest of the function should return ip address, subnet mask, default gateway, primary and secondary dns, mac address etc etc



Charlie Benger-Stevenson
Hart Hill IT Ltd
 
Actually, if you don't mind your function not being multi-thread safe, you can use a static variable:

Code:
const char* getLocalHostName()
{
   static char buf[1024];
   if ( gethostname( buf, 1024 ) == 0 )
   {
      return buf;
   }

   return NULL;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top