- Accidentally - for example when a 3rd party company develops a client with a bug in, and discovers that this client bug activates a server bug which is exploitable
- Source code analysis - the owners of the source or someone else manually or automatically scan the source code for problems
- "Fuzzers" - these are programs which deliberately throw junk at network servers.
I would like to add to this list two things:
- Trial and error
- Thinking like an attacker

They are closely related I might add.

Buffer Overflows are very popular since the (in)famous paper 'smashing the stack....." was released.
They basicly work like this: put the half empty glass and the half full glass together and add a drop, the glass will overflow.
Many people are to impatient to just add one drop a time so they drop another glass in the allready full glass and post their overflow to a mailing list like vuln-dev waiting for someone to calculate where the glass gets overflown.

To think like an attacker you would start for example with something like 'how will i get internet explorer to open calculator when someone browses my site'. You study all code that is available to you, MSDN (like mentioned) Javascript/VB referances and try and try and try. Eventually you will find something (or not).

To give away a little: set up a site with a WMP player file on it and set your IE to high regarding scripts and stuff.
Now visit the url that will play the file. Some javascript prompts will pop-up. For example type yes (allow) on the first one and no (deny) on the second one. A pop up will apear telling you a 'stack overflow has occured'.

Well I hope this has explained a bit