@AndréBorie is correct. Compilers and the corresponding configuration will not be well vetted for security issues, so generally speaking you should not compile untrusted code.
The risk is that a buffer overflow or some type of library execution vulnerability is exploited, and the attacker gains access to the (hopefully non-
root!) user account that ran the compiler. Even a non-
root hack is serious in most cases. This could be elaborated on in a separate question.
Creating a VM is a good solution, to contain any potential exploits so they cannot harm the rest of your application.
It is best to have a template Linux VM you can launch as needed with a clean slate compiler environment.
Ideally you would throw it away after every use, but this may not be strictly necessary. If you isolate the VM well enough, and properly sanitize response data from the VM, which you should be doing anyway; then the worst a hack could do is DoS or create false compile times. These are not serious issues on their own; at least not nearly as serious as accessing the rest of your application.
However, resetting the VM after every use (i.e. instead of daily) does provide for a more stable environment overall and can improve security in certain edge cases.
Some OSes provide Containers as an alternative to VMs. This may be a leaner approach, but the same principles apply.