Click here to Skip to main content
15,892,005 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
C++
PBYTE m_pSectorBitmap = new BYTE[512];
memset(m_pSectorBitmap, 0xFF, 512);

For the above code snippet, i am expected to get a BYTE array with FF upto 511 positions, But for some reasons i am getting another 16 Byte that is I am getting 511 BYTES of FF and another 16 Bytes of JUNK values. Can someone explain y it is so. What should i do to get exactly 511 Bytes of FF.

I have tried the same with 128 Bytes, still getting the same problem, Is it so generic, or is it not at all a problem ?

Thanks,
Sajith
Posted

1 solution

The way that pointers work is that they point to one memory location. When you allocate memory (returned in a valid, non-NULL pointer), the pointer is set to the first byte in the newly allocated memory. If the allocation is successful, you get to use the exact number of bytes that you requested, and no more. Looking at the data beyond what you requested is called "undefined" behavior, and can result in several behaviors that you can not control (maybe it is "padding" that is really also allocated, it might be overhead for your allocation, invalid memory, another allocation, or something else).

The memory you point to in the example you provide is only valid for the first 512 bytes. If you look beyond that you are breaking the rules. What seems to be junk to you is used by the memory allocation system, and you are not entitled to access it.
 
Share this answer
 
Comments
gssajith87 23-Mar-13 20:27pm    
Thanks Brydon, So i take it as, it is by default, showing up some values in the memory (always a 16 byte padding at end of my pointer)that i need not worry about..
Steve44 23-Mar-13 20:48pm    
You should not worry about anything BUT the amount of bytes you allocated as this is everything that is promised to you. Everything outside that range, before your allocation or after your allocated number of bytes should not be touched or interpreted by you.
So it seem like the 512 bytes you allocate are correctly filled and everything else: you have no guarantees what is in there (maybe dragons?)
H.Brydon 24-Mar-13 15:41pm    
No, that is not correct. If you ask for 512 bytes, then you can look at that 512 bytes AND NO MORE. Anything outside of that is not yours to look at, make assumptions about or attempt to use for any purpose.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900