运行-Time Check Failure #2 - 变量 'length' 周围的堆栈已损坏

Run-Time Check Failure #2 - Stack around the variable 'length' was corrupted

Hi All,

I am working on changing our application to support unicode characteristics . Hence while doing the changes i had to convert all char to wchar_t and we had some wrapper stream classes which i converted to support wchar_t . Now my issue is while doing the change to the below code i encounter Run-Time Check Failure #2 - Stack around the variable 'length' was corrupted. though if i continue i get the proper values . Please let me know how to get rid of this error.

FDIStream&  
FDIStream::
operator>>(std::wstring& data)
{
    if (CanReadData())
    {
        int length = -1;
        *this >> length;

        if (length >= 0)
        {
            // See if length is a valid value (not pass eof)
            if (length > GetLength()) {
                throw FDException("Corrupted file");
            }

            wchar_t* buffer = new wchar_t[length];

            try
            {
                ReadBytes(buffer, length);

                data = std::wstring(buffer,length); 
            } catch (...)
            {
                delete[] buffer;
                throw;
            }

            delete[] buffer;
        }
    }

    return *this;
}

假设生产者写入流的length的值是通过data.length()获得的,那么它代表字符的数量字符串,而不是字节数。我从它的名字假设 ReadBytes 正在尝试 length 字节,这就是问题所在。您需要阅读 length 个字符。

此外,如果您尝试向流写入 length 个字节而不是 length 个字符,您可能会在生产者中遇到镜像错误。