To answer your question, it is legal if you do it right. There is a Meta.stackoverflow question that goes into some of the details, and gives a list of sites that do such:
Is it legal to copy Stack Overflow questions and answers?Is it legal to copy Stack Overflow questions and answers?
That's an edge-case, though likely infringing. I'll poke some of the SE people who check into these things.