Good day! I am trying to learn how to allocate memory dynamically using winapi.

{ HANDLE hHeap = GetProcessHeap(); TCHAR *strName = (TCHAR*)HeapAlloc(hHeap, 0, 1 * sizeof(TCHAR)); lstrcpy(strName, _T("Hello")); MessageBox(0, strName, 0, 0); HeapFree(hHeap, 0, strName); } 

The problem is that I don’t understand why this code works normally .. It seems like I allocate memory for 1 character, but I bring 5 characters there (this is not including the terminating zero), moreover, even if I instead of 1 * sizeof (TCHAR ) I will write 0, it also works and gives a full Hello. Explain how it works? Are there any other non-related threads in this code? Thank.

  • 2
    The question "why this code works " in the world of C and C ++ does not exist. Compiled, but erroneous, code generates undefined behavior . Which for the time being can manifest itself externally as an allegedly “working” code. That is what you are watching. - AnT

1 answer 1

HeapAlloc allocates and returns a pointer to a 1-TCHAR memory block. But the physical memory (or even virtual) does not end there. Your lstrcpy uses it, but "without demand." Most likely, there was nothing important and therefore the program "works." If you allocate one more block of memory immediately after the first one, then it is possible that lstrcpy will overwrite it and then the code using this second block will most likely work incorrectly, except if you did not rely on this rewriting. Although, what is “wrong” is a very big question! :)

Perhaps the fact is that HeapAlloc allocates a block of sufficient size, and most likely, a larger one.