Assuming you're coming into the Estacion de Atocha (rather than Chamartin), I would recommend the
Hostal Barrera . It's about a 5 minute walk up Calle Atocha from the train station and is a comfortable, quiet hostal with a friendly and helpful staff.
As in any big city, Madrid has some areas to avoid walking alone in at night but is, for the most part, safe.