Greetings There is such a code fragment:

#define _CRT_SECURE_NO_WARNINGS #include <Windows.h> #include <tchar.h> #include <cstdlib> #define SIZEBUF 4 #define SIZEQUEST 30 #define RAD 10 int main() { int nCountAtt = 0; wchar_t* pQuest = new wchar_t[SIZEQUEST]; wchar_t* pBuff = new wchar_t[SIZEBUF]; _itow(nCountAtt, pBuff, RAD); pQuest = L"Вы загадали число "; wcscat(pBuff, L"?"); wcscat(pQuest, pBuff); //здесь возникает ошибка delete[] pBuff; delete[] pQuest; return 0; } 

In the marked line of code, the exception described in the header occurs. I understand that going beyond the allocated memory is happening, but I cannot understand why this is happening. Tell me the reason, please.

    1 answer 1

    There are more than one mistakes here :)

     wchar_t* pQuest = new wchar_t[SIZEQUEST]; pQuest = L"Вы загадали число "; wcscat( pQuest, pBuff ); 
    1. You allocate memory, you assign its address to the pQuest pointer
    2. Immediately lose this value by overwriting the pointer with the address from the static data segment.
    3. Add something else to this data, trying to get into the readonly area.

    Probably meant something like this:

     wchar_t* pQuest = new wchar_t[SIZEQUEST]; wstrcpy( pQuest, L"Вы загадали число " ); wcscat(pQuest, pBuff); 

    But there will also be an error: there is no control over the length of the data recorded in pQuest ... And what to do with it is already on your own :)

    • Thank you so much, chew. I went to correct the code. =) - SuDex