IG-88 was programmed to kill, but apparently he was not told to follow orders, because he killed his creators, and went into business for himself. (Itself?)
K2SO was reprogrammed, and obeyed rebel orders, because he was programmed to do so. Killing didn't seem to be a problem, so long as they were considered "hostiles".
R2D2 was sold to <PERSON>, but continued to be loyal to his mission to find Ben.(Another internal secret map? REALLY ARTOO?) Obviously his programming knew the sale was not legal, and he still had a mission to fulfill.
C3P0 Told <PERSON> in "A new Hope" that he wanted to take a nap (Shut down to recharge?) after his bath, and asked <PERSON>'s permission. He made sure he was not needed, but had enough control over himself to power cycle. He also apparently could turn himself back on, because he said he TRIED to stop <PERSON> from leaving, and then hid himself to avoid being punished.
This concept is shown again in "The Force Awakens" when <PERSON> had been in "low power mode" for a while but was able to turn himself back on when the proper time arose for him to share his section of the map.
"I didn't hit it THAT HARD, it must have had some sort of self-destruct" Was what <PERSON> said after shooting the Imperial Probe-Droid on Hoth, and it's explosion. "There isn't much left". So the droid knew it might be captured and hacked, and either CHOSE to end itself, or it was programmed to do so.
If a droid can turn itself on and off, and can even kill itself, chances are, it would not be hard to erase it's own memory. 865
<PERSON> is pretty quick to zap ANYONE with a tazer. Rerouting some amperage inside wouldn't be that hard for him to do, astromech droids repair ships IN FLIGHT and DURING COMBAT, as seen in "The Phantom Menace". So quick thinking and improvising a memory wipe shouldn't take long.
When <PERSON> was hacking the DeathStar, it DID take a few moments, someone hacking him should also take a tiny bit of time, but Artoo is quick.
K2SO was also Quick to hack another droid, but he was VERY familiar with that model, and how to hack it. Even though he used the quick Robo-Cop style stab and hack, I think <PERSON> would have been able to nuke his files before they were discovered.
Keeping mission files loaded in short-term ram would be another option. Anything on e-prom or hard drive (yes they use hard drives, watch "Rouge One") Could be pulled up if he were disabled, by lets say.. an Jawa droid stunner? But anything in ram would be lost when power cycled, or just from the sheer power coursing through his circuits from the discharge.
R2D2 had proven his loyalty many times. But, he could have also been blindly following orders as he was programmed to do. 865