Counter variable gets reset to 0 without resetting it(Mega)
You never reset your b pointer. The first time through it works its way through the memory reserved for buf. The second time through your loop it's already at the end of that memory and you then start incrementing (and filling) past that overwriting other variables - the first of which sounds like it might be n - so *b++=data is writing data (245) to n.

You need to reset b each time you go through loop so it starts at the beginning of the array each time:

b = buf;