C++ Pointer changed address, now it won't delete it (Fails)

(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 it looks like: http://s21.postimg.org/wr94yponr/Capture4.png

i
1
2
3
4
5
6
7
8
9
10
11
12
13
f (test == "MapleStory")
{

wchar_t *titlePTR = new wchar_t[30]; <-- Example Address: 051
cout << titlePTR;
wchar_t *bodyPTR = new wchar_t[20];
titlePTR = L"MapleStory"; <-- address is changed here.
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;
Last edited on
1
2
3
wchar_t *titlePTR = new wchar_t[30]; //loading the gun
titlePTR = L"MapleStory"; //pointing at your foot
delete[] titlePTR; //shooting 
¿what's your question?
use strcpy(...) in lines 7 and 8
ne555 wrote:
1
2
3
wchar_t *titlePTR = new wchar_t[30]; //loading the gun
titlePTR = L"MapleStory"; //pointing at your foot
delete[] titlePTR; //shooting  
1
2
3
wchar_t *titlePTR = new wchar_t[30]; //pointing at the target
titlePTR = L"MapleStory"; //pointing at your foot
delete[] titlePTR; //shooting  
FTFY

Pointers are called pointers because they point to memory address. Any operation you perform on them make their address change. For example lines 7 and 8 make it point to completely new memory locations.
You should work with values pointers point to instead. For example, you might use srncpy as Konstantin2 suggested: wcsncpy(titlePTR, L"MapleStory", 30);
Last edited on
Use std::wstrings, forget all that new/delete nonsense.
At line 7 your are changing the pointer itself to point to L"MapleStory". You want to copy the string to array that you've already (the one that titlePTR points to. If you were using char instead of wchar, you could use:
strcpy(titlePTR, "MapleStory");
But I don't know what is available for this with wide chars.

If you're goal is just to learn about memory allocation then I suggest you change the code to use char instead of wchar_t. That way you'll remove another potential source of problems.

Hope this helps.
Changing the char type isn't going to change anything.
Topic archived. No new replies allowed.