0

I have a function called ReversedIPAddressString which takes IPAddress as a TCHAR* and then returns reveresed IPAddress as TCHAR*. I am able to get reversed IP fine but when I passed this TCHAR* pointer(reversedIP) to some other function(let's say dns.query(TCHAR*)),IP value always junk. I am wondering what I am missing?

I am pasting my code here for your reference...

Caller Method:

bool DNSService::DoesPtrRecordExixts(System::String^ ipAddress)
{
    IntPtr ipAddressPtr = Marshal::StringToHGlobalAuto(ipAddress);
    TCHAR* ipAddressString = (TCHAR*)ipAddressPtr.ToPointer();
    bool bRecordExists = 0;

    WSAInitializer initializer;
    Locale locale;

    // Initialize the identity object with the provided credentials
    SecurityAuthIdentity identity(userString,passwordString,domainString);
    // Initialize the context
    DnsContext context;
    // Setup the identity object
    context.acquire(identity);

    DnsRecordQueryT<DNS_PTR_DATA> dns(DNS_TYPE_PTR, serverString);
    try
    {
        bRecordExists = dns.query(ReversedIPAddressString(ipAddressString)) > 0;
    }
    catch(SOL::Exception& ex)
    {
        // Free up the pointers to the resources given to this method
        Marshal::FreeHGlobal(ipAddressPtr);

        if(ex.getErrorCode() == DNS_ERROR_RCODE_NAME_ERROR)
            return bRecordExists;
        else
            throw SOL::Exception(ex.getErrorMessage());
    }

    // Free up the pointers to the resources given to this method
    Marshal::FreeHGlobal(ipAddressPtr);

    return bRecordExists;
}

Called Method:

TCHAR* DNSService::ReversedIPAddressString(TCHAR* ipAddressString)
{
    TCHAR* sep = _T(".");
    TCHAR ipArray[4][4];
    TCHAR reversedIP[30];
    int i = 0;

    TCHAR* token = strtok(ipAddressString, sep);
    while(token != NULL)
    {
        _stprintf(ipArray[i], _T("%s"), token);
        token = strtok((TCHAR*)NULL, sep);
        i++;
    }
    _stprintf(reversedIP, _T("%s.%s.%s.%s.%s"), ipArray[3], ipArray[2], ipArray[1], ipArray[0],_T("IN-ADDR.ARPA"));

    return reversedIP;
}

DNS.Query method declaration:

int query(__in const TCHAR* hostDomain, __in DWORD options=DNS_QUERY_STANDARD)

Hope to get help from you.

Thanks in advance!

Ramani

Sergei Danielian
  • 4,938
  • 4
  • 36
  • 58
user1358784
  • 115
  • 2
  • 2
  • 14

1 Answers1

0

You're returning a pointer to the local array TCHAR reversedIP[30]; which is allocated withing your function ReversedIPAddressString. When this function exits, your array becomes out of scope - it does not exist anymore. This is undefined behaviour.

You should return a string object instead, for example std::basic_string<TCHAR>

See this question: pointer-to-local-variable

Community
  • 1
  • 1
Jem
  • 2,255
  • 18
  • 25
  • I fixed this issue by converting array to pointer TCHAR* reversedIP = new TCHAR[30] and then deleted memory from called method. Thanks Jem for your insight! – user1358784 May 18 '12 at 12:24