What is the proper way of sending an array of WCHAR to winproc as a LPARAM?

So I've got a corruption of the heap problem and wondered if it could have to do with how I work with some arrays. Actually, at some point I have a few messages like this sent to my WinProc:

SendMessage(hwnd, LOG_ADD, NULL, (LPARAM)L"Initializing winsock... ");

LOG_ADD is defined as 104. Inside WinProc, when msg==LOG_ADD, the following happens:

case LOG_ADD:
            {
                pGame->pMessageLog->PutToLog((WCHAR*)lParam);
                pGame->pD2DResources->OnRender(pGame->pMessageLog);

There is MessageLog::PutToLog(WCHAR[]):

void MessageLog::PutToLog(WCHAR txt[])
{
    int strLen=wcslen(txt);
    int logLen=wcslen(logHistory);

    WCHAR* pWCHAR = txt;

    int x=0;

    // Counts the number of '\n' into wString and adds that number to nLogLines
    for(x=0; x<strLen; x++)
    {
        if(pWCHAR[x]=='\n')
            nLogLines++;
    }

    pWCHAR = logHistory;

    x=0;
    while(nLogLines>5)
    {
        if(pWCHAR[x]=='\n')
            nLogLines--;
        x++;
    }

    if(x!=0)
    {
        for(int y=0; y<logLen-x; y++)
        {
            pWCHAR[y]=pWCHAR[y+x];
        }
    }

    wcscat (logHistory, txt);
}

Could this explain the corruption problem? Actually, when I remove all the SendMessage(hwnd, LOG_ADD...) lines, the corruption doesn't appear a few lines later when the compiler executes the line "struct hostent* host;" or "if((host=gethostbyname(server))==NULL)".

Upvotes: 0

Views: 854

Answers (1)

Johann Gerell
Johann Gerell

Reputation: 25591

You asked in a comment:

is this the proper way of sending a WCHAR array as a LPARAM and sending it to another function to use?

Sure, as long as you know what you pass at the call site and make sure you treat it (cast it) as the type it actually is in the window procedure, this is perfectly fine.

Just make sure you're properly handling any pointers to memory that might be invalid at the time you access it. For instance if you post a message instead of sending it and pass a pointer to memory that runs out of scope before the receiver handles the message.

Also remember to properly initialize any data you send...

Upvotes: 2

Related Questions