1

please look this code , in my machine , it do not raise error , but I do not understand why can I copy more bytes than VirtualAlloc allocated,is this operation safe ?

    PBYTE pNewBuffer = (PBYTE) VirtualAlloc(NULL,3,MEM_COMMIT,PAGE_READWRITE);
    BYTE FlagThree[] = {'a', 'b', 'c', 'd','e','f','g'};
    CopyMemory(pNewBuffer,FlagThree,sizeof(FlagThree));

I allocate 3 bytes but copy to the memory 7 bytes.

Paul R
  • 208,748
  • 37
  • 389
  • 560
yangl
  • 337
  • 1
  • 3
  • 18

3 Answers3

3

This is not undefined behavior. In fact, it's totally defined, since documentation explicitly states that "If the lpAddress parameter is NULL, this value (dwSize) is rounded up to the next page boundary".

So until you exceed page size, it's pretty safe.

2

VirtualAlloc rounds your allocation up to the nearest allocation boundary, so although you are requesting 3 bytes you'll actually allocate more as the allocation granularity is 64K.

Because of this you are able to write more that the 3 bytes you requested. However, as mentioned in the comments, this is undefined behaviour and you shouldn't do it.

Sean
  • 60,939
  • 11
  • 97
  • 136
0

Whilst the other answers to this post (round up) are totally correct in this specific case, your question leads me to think that you should understand what C++ calls undefined behavoir.

In most other situations in C++ unlike languages like Java or C#, doing something 'bad' may not cause the program to immediately crash but cause it to possibly malfunction in weird ways. Or just run as you expect. Its just not defined what will happpen. Read up on it.

Mike Vine
  • 9,468
  • 25
  • 44