Nope... you didn't asked to make it safer. Your words (post #1): "...I need to understand how to make it not vulnerable to these attacks..."
To undestand something you need to know WHY!
And laserlight already answered your question and even post a code making it "not vulnerable".