views:

75

answers:

1

I would like to understand a bit more about memory and I was unable to find it from Google, please forgive me if this is silly question.

How come the following code, accessing memory address 0(and up to 65535) in C# would throw NullReferenceException

byte* pointer = (byte*)0;

byte test = *pointer;

Thanks a lot in advance!

+2  A: 

This is a design feature of Windows itself. In order to catch programmer mistakes early in the development cycle, the virtual addresses from 0 to 64K (- 1) are invalid in all processes.

Timores
I am sorry may I ask what do you mean by "virtual addresses from 0 to 64K (- 1) are invalid in all processes." because I thought this are real address, many thanks!
Terry
Do you have a reference for that?
0xA3
Terry,If you are running Windows "real" addresses don't really exist.The simple way to look at it is that each application "thinks" it is running on its very own x86,x64 computer. It has its own address space et.al. ..so..A pointer to say 0xDEADBEEF in one application does not point to memory address 0xDEADBEEF in another. Fun, isn't it :)
Rusty
Thank you very much Rusty and this is a new concept to me. May I ask [1] why is it done in this way(as in "0xDEADBEEF in one application does not point to memory address 0xDEADBEEF in another")[2] why is a program not being able to address the first 16bits of memory? Thanks!
Terry
[1] If all applications shared the same address space what would stop application X from arbitrarily writing into memory being used by application Y ?...that would be bad...It would of course get worse if application X had a hard coded pointer to 0xDEADBEEF...what if that was being used by application Z. So in Windows...every Process gets its own kinda of Virtual machine, hence Virtual Address space is often the term used. [2] If memory serves, this is way back, the first 64k of a process was/is reserved for the process and as memory was broken into 64k pages, page 0 was reserved. Dos History.
Rusty
Hi Rusty, thank you very much for your time again. May I ask what does it mean by "memory was broken into 64k pages, page 0 was reserved"? Does it mean the first 64k is page 0 and what is it reserve for? Thank you very much!
Terry
Yes, a page is 64K and page 0 is the first 64K. And it is reserved to catch references to null pointers.
Timores
@0xA3, see http://msdn.microsoft.com/en-us/library/ms810627.aspx, specifically the Note in the "Reserved addresses" sub-section.
Timores