Named pipe messages corrupted (Win32,C)
<p>I have some pipe communication code - received bytes are no match for sent bytes.
There is a loop where 'CallNamedPipe' is called to send messages to server.
Now only 1st message is received intact, all the rest are received partially filled with 0xCD byte.
It seems, that when I free the memory after sending - it is still being read by server thread.
MSDN says that CallNamedPipe() is a complete message sequence: open pipe, sent bytes and close the pipe.
So, this seems strange to me. I must mention, that this code is built by VC++ 6.0 - a very old compiler. Code runs on Windows 7, maybe I need to use compatibility mode? Both client and server executables run on the same physical system, not remotely. Client uses CreateProcess() on startup to start the server. The messages are sent much later on, so racing conditions should not matter, I hope.</p>

<p>Thanks for any advice.</p>

<pre><code>============ Client side (pseudocode): ============
for (iPiece=0; iPiece &lt; nPieces; ++iPiece)
{
    buffer = malloc (2048);

    // copy some data bytes into buffer (1..2048 bytes)
    // log 1st 32 DWORDS from message about to be sent

    if (! CallNamedPipe (name, buffer, nBytes, ..., 1000))
    {
        // diagnostics: call to GetLastError(), etc.
    }
    free (buffer);
}

============ Server side (pseudocode): ============
DWORD __stdcall ServerThreadProc (PVOID p)
{
    UINT    cbMaxMsg = 0x10000; // 64K for a pipe message
    PVOID   buffer = malloc (cbMaxMsg);
    HANDLE  hPipe;
    BOOL    fAbort = 0;

    hPipe = CreateNamedPipe (name, PIPE_ACCESS_DUPLEX,
        PIPE_WAIT | PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE,
        PIPE_UNLIMITED_INSTANCES, cbMaxMsg, cbMaxMsg, 1000, NULL);

    while (fAbort == 0) // one of pipe messages sets fAbort=1, so thread can return.
    {
        if (ConnectNamedPipe (hPipe, NULL))
        {
            DWORD   bytesLoaded = 0;

            ReadFile (hPipe, buffer, cbMaxMsg, &amp;bytesLoaded, NULL);
            if (bytesLoaded)
            {
                // log 1st 32 DWORDS from received message
                // process the pipe message (switch/case)
                // data may be written back to client after processing

                FlushFileBuffers (hPipe);
            }
            DisconnectNamedPipe (hPipe);
        }
        else
        {
            // diagnostics, GLE(), etc.
        }
    }

    free (buffer);
    CloseHandle (hPipe);
    return 0;
}
</code></pre>