Archived

This topic is now archived and is closed to further replies.

barazor

returning local variables(yet again)

Recommended Posts

barazor    122
i was wondering, since i just now found out that returning pointers to a local variable is a great way of causing some major bugs(im self taught), i have decided to rewrite some of my code. heres what it would have looked like before:
    
char* GetLocalIP()
{
    hostent* localInfo = gethostbyname(NULL);  // get localhost name

    in_addr addr;
    memcpy(&addr,localInfo->h_addr_list[0],sizeof(in_addr));
    return inet_ntoa(addr);
}
  

that looks like it would have messed up eventually

would it be safe to write it like this?
      
bool GetLocalIP(char *&dest)
{
    hostent* localInfo = gethostbyname(NULL);  // get localhost name

    in_addr addr;
    memcpy(&addr,localInfo->h_addr_list[0],sizeof(in_addr));
    char* temp = inet_ntoa(addr);
    int len = strlen(temp);
    memcpy(dest,temp,len);
    dest[len] = 0;
    return 1;
}
    
that is just a hacked together example of what i think i should maybe do(havent even tested it yet), any help with this subject will be well appreciated edit - oops forgot to make dest a reference Edited by - barazor on December 9, 2001 4:18:00 PM

Share this post


Link to post
Share on other sites