Malviolio serves several functions. First of all, he is comic relief. He is arrogant and pompous and, in many ways, he gets his comeuppance when he is tricked into thinking Olivia loves him.
Also, Malvolio's character acts as a foil to Viola's. He is foolishly forward in his advances while she is cautious in hers. He is outspoken, and takes the letter he receives at face value, assuming it is "his lady's "c"s, "u"s and "p"s that he sees. The fact that he is so easily duped here suggests that, though he speaks much, he knows little about Olivia, so little that he can't even recognize her handwriting, never mind the content of what she says.
Viola, on the other hand, is not quick to presume she is loved. While Malvolio is forward, Viola is reticent. She hints at her feelings for Orsinio but does not share them with him (beyond the story she tells). In contrast to Malvolio, Viola has studied her love and knows everything there is to know about him.
By juxtaposing Viola's approach to love with Malvolio's, we see her virtue as plainly as we see Malvolio's vice.
More info on Malvolio and the "Malvolio Problem"
Malvolio is there to amplify the comedy of the play and also to be a sort of villain who gets his comeuppance. He is not a villain in terms of doing bad things, it's his character that is annoying and that the audience enjoys seeing get fooled and humiliated.