You're confusing RAM with ROM.
ROM is the 40MB and it's basically the built-in hard drive of your phone. It's space for you to store crap on, like apps, photos, etc.
RAM is usually at or under 20MB and is the same thing as the RAM on your computer. it's called Random Access Memory, and it's basically space for the processor to use to temporarily store processes. Think of it like a desk. it's the stuff that you're currently working on, and as you get mroe and more stuff, you make little piles here and there. Eventually, if you try to do too many things at once, your desk becomes too cluttered and you have to get rid of something.
I realize that's a shady comparison but it's the best I can do. That's why you get "out of memory" errors, cause you're out of RAM, not ROM.