Are virtual machines safe for this? The answer is the same as for a lot of questions of the form "Is X safe?": no, it's not absolutely safe.
As described elsewhere, bugs in the virtual machine or poor configuration can sometimes enable the malware to escape. So, at least in principle, sophisticated malware might potentially be able to detect that it's running in a VM and (if your VM has a vulnerability or a poor configuration) exploit the vulnerability or misconfiguration to escape from your VM.
Nonetheless, it's pretty good. Probably most malware that you run across in the field won't have special code to escape from a VM.
And running the malware in a VM is certainly a lot safer than installing it directly onto your everyday work machine!
Probably the biggest issue with analyzing malware samples in a VM is that some malware authors are starting to get smart and are writing their malware so that it can detect when it is run in a VM and shut down when running inside a VM. That means that you won't be able to analyze the malicious behavior, because it won't behave malicious when it's run inside a VM.
What alternatives are there? You could set up a sacrificial machine on a local machine, install the malware on there, then wipe it clean. Such a test network must be set up extremely carefully, to ensure that the malware can't propagate, can't spread to other machines of yours, and can't do any harm to others.
References: