Click here to Skip to main content
15,891,777 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a function

C++
void ModifyString2 (WCHAR *szString)
{
    // Declare a sample wide character string.
    int nLen = wcslen (szString);
    wcscat_s(szString, MAX_STRING_SIZE, L"-Modified" );
}


I am calling this function from main function.

C++
void main ()
{
    WCHAR szString [MAX_NAME_LENGTH] ;
    wcscpy_s(szString, MAX_NAME_LENGTH, L"This is Some String");
    printf ("Before Call String  Value=[%s]", szString);

    ModifyString2(szString);

    printf ("Before Call String  Value=[%s]", szString);
}


When I debug this program, and exit from main i get an error

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


what i am doing wrong ?

What I have tried:

instead of allocating szString on stack, i tried it with heap,

like
C++
void main ()
{
    WCHAR * szString = new WCHAR [MAX_NAME_LENGTH] ;
    wcscpy_s(szString, MAX_NAME_LENGTH, L"This is Some String");
    printf ("Before Call String  Value=[%s]", szString);

    ModifyString2(szString);
    
    printf ("Before Call String  Value=[%s]", szString);
    delete szString;
    return 0;

}


This may be due to a corruption of the heap, which indicates a bug in MFCClient.exe or any of the DLLs it has loaded.


Not sure, what i am doing wrong, I am using Visual Studio 2010 ultimate, on a windows box.

please Help.


-praveen.
Posted
Updated 6-Dec-19 23:19pm
v2

1 solution

Most likely because the values of MAX_NAME_LENGTH and MAX_STRING_SIZE are different. You should pass the length of the buffer in to the ModifyString2 function, so it uses exactly the same length as the original buffer. Something like:
C++
void ModifyString2 (WCHAR *szString, int nlen)
{
    wcscat_s(szString, nlen, L"-Modified" );
}


[edit]
And change the call to:
C++
ModifyString2(szString, MAX_NAME_LENGTH);

[/edit]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900