简体   繁体   中英

Finding new memory address? C++

(I tested the address because I was getting errors and I found out the address changed before it was deleted, by the time the delete is called the titlePTR has already changed its address and it is giving me an error saying " BLOCK TYPE IS VALID " I heard this is when you try to delete a pointer that wasn't made by new (So that made me think about the address)

Btw I know I don't have to make a dynamic array but I am reading a book and it is saying to practice saving memory for times where your program doesn't need to run the code. I posted on a few other places and people always nag about "Don't use new blah blah blah"

Here is what is says when it trys to delete titlePTR or bodyPTR : http://postimg.org/image/gt0f8kufn/

if (test == "MapleStory")
{
    wchar_t *titlePTR = new wchar_t[30]; <-- Example Address: 051
    cout << titlePTR;
    wchar_t *bodyPTR = new wchar_t[20];
    titlePTR = L"MapleStory";
    bodyPTR = L"Launching MapleStory...";
    MessageBox(NULL, bodyPTR, titlePTR, MB_OK | MB_ICONINFORMATION);
    ShellExecute(NULL, L"open", L"GameLauncher.exe", NULL, L"C:\\Nexon\\MapleStory", 1);
    cout << endl << titlePTR; <-- Example Address: 0601 
    delete[] titlePTR;
    delete[] bodyPTR;
}
wchar_t *titlePTR = new wchar_t[30];   // (1)
titlePTR = L"MapleStory";              // (2)
delete[] titlePTR;                     // (3)

This allocates memory and stores the address of the memory in the variable (1). Then you overwrite it with a new address (2). And then you delete the new address (3), instead of the allocated memory. So your problem is that the assignment in step (2) doesn't use the buffer you prepared but creates a new buffer.

To fix, just do:

const wchar_t *titlePTR = L"MapleStory";

And don't delete of course, since you didn't allocate any memory using new .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM