Run time error in counting sort

#include
#include
using namespace std;
int main() {
int n,maxi,i;
cin>>n;
int a[n],freq[99999];
for(i=0;i<n;i++)
{
cin>>a[i];
if(i==0)
{
maxi=a[i];
}
if(i>0&&maxi<a[i])
{
maxi=max(maxi,a[i]);
}
freq[a[i]]++;
}

for(i=0;i<=maxi;i++)
{
    while(freq[i])
    {
        cout<<i<<" ";
        freq[i]--;
    }
}



return 0;

}