I agree with the idea that most likely adrenaline would cause you to empty the mag. That's probably what I'd do.
To the original question, I've slept with a gun under my pillow before. I never felt that there was a risk of an accidental or negligent discharge doing it this way, but it wasn't as easy to reach it as I thought. I found that if I moved around in my sleep, the gun shifted and was never quite in the same place in the morning. Sometimes it moved as much as 8 or 10 inches. If you have to reach for it in the night while you're laying down, you have a limited reach if you lie on your back or on your side. If the gun has moved even half a pillow-length, you are less able to reach for it and can lose valuable time fishing for it.
Since then, I put it on the nightstand. I can reach that way with either hand and it never shifts. It's in the same place every time and it's instinctual to reach for it. Plus, I'm pretty sure there's no way some guy with a machete could get through my house to my bedroom without me being ready. At the very least, he'd trip over a bunch of junk in the dark!