When Jafar becomes a genie at the end, he then suddenly drops back into the lamp and is trapped. What happened?
And did the Genie get free because Aladdin wished it?
Genies are given power in exchange for servitude. When Jafar wished for the powers like Genie, he got his wish. But it's exactly like the saying "be careful what you wish for, you might just get it". Jafar got locked away until a master comes to let him out. Which happens in the sequel.
And yes, Genie was freed using Aladdin's third wish, which he had promised him earlier in the movie. An act of kindness that freed Genie from his servitude.
Jafar wished to become an all-powerful Genie, and he got what he asked for.
Jafar is an incredibly power-hungry person. We see he's already mastered at least some forms of magic (as demonstrated by his hypnotic staff), and we know that his position as Royal Vizier gives him access to the ear of the most powerful man in Agrabah — the Sultan.
We also see that he isn't content where he is. His initial plan to gain power is to marry Princess Jasmine, which would make him the next Sultan, but when he regains the lamp of the Genie he forgets about that altogether, and instead simply takes power instead.
Fortunately, Aladdin knows how power-hungry Jafar is, and tricks him into wishing to become a Genie — which although grants him unstoppable power, also traps him in a magic lamp and forces him to serve whoever rubs it. That's the downside of being a Genie, and Jafar had forgotten all about it in his lust of power.
As for the Genie himself — yes, he is freed because Aladdin wishes it. Aladdin is granted three wishes by the Genie, and the other two he uses are;
To save his life. This is when Aladdin is trapped underwater by Jafar's men - the Genie sort of makes this wish for him, but it still counts thanks to the fact that Aladdin had tricked the Genie into freeing him from the cave earlier, at which point the Genie says;
"All right, you ba-a-a-ad boy. But no more freebies."
The Genie, Aladdin (1992)
In short: Jafar is tricked into trapping himself as a Genie, and Aladdin does use his final wish to free the Genie.