Two part question:
1-How do memory resident viruses stay in memory after the program which loaded them is finalized? If all memory is automatically deallocated by the OS once a program is finished, how could then the malicious code survive? Does it instead create a separate executable file which then runs in background then starts it? Or it corrupts the OS in some way?
2- How does the virus captures traps and interrupts or modifies the OS RAM bitmap? Shouldn't the OS forbid this?
From Tanembaums OS book:
"So far we have assumed that when an infected program is executed, the virus runs, passes control to the real program, and exits. In contrast, a memory-resident virus stays in memory all the time, either hiding at the very top of memory or perhaps down in the grass among the interrupt vectors, the last few hundred bytes of which are generally unused. A very smart virus can even modify the operating system's RAM bitmap to make the system think the virus' memory is occupied, to avoid the embarrassment of being overwritten.
A typical memory-resident virus captures one of the trap or interrupt vectors by copying the contents to a scratch variable and putting its own address there, thus directing that trap or interrupt to it. The best choice is the system call trap. In that way, the virus gets to run (in kernel mode) on every system call. When it is done, it just invokes the real system call by jumping to the saved trap address."