Use defensive programming
If Windows was coded with the same level of defensive programming as used to be common in minicomputer operating systems there would be far less security problems in it.
An example (in pseudo code) of the sort of coding that used to be common (taken from RSX11M operating system)
System function request from user program
Is the function number in range - if NO then reject the request
Does the program have the right to call the function - if NO then reject the request
Has the program passed the correct number of parameters - if NO then reject the request
Are all the parameters accessible - if NO then reject the request
If the above checks are OK then pass the request to the system function which (for most requests) will perform further checks and reject the request if any fail
The assumption should always be that any request is invalid and only if all checks are passed should it be acted on.
Unfortunately a lot of current code omits the vital checks resulting in security holes.