0

What is wrong in my code? Why am I getting a segmentation fault?

void sort(int values[], int n)
{
int aux_list[65536] = {0};

//map the count of values in the values list as the index of the aux list
for(int i = 0; i < n; i++)
{
    aux_list[values[i]]++;
}


int num = 0;

for(int i = 0; i <= 65536; i++)
{
    if (aux_list[i] > 0)
    {
        for (int a = 0; a < aux_list[i]; a++)
        {
            values[num] = i;
            num++;
        }
    }

}
} 
1

If you array is declared with 65536 buckets, then aux_list[65536] is outside the bounds (remembering that arrays are zero-indexed). So what happens in your loop when i == 65536?

| improve this answer | |
  • Hi there!! Thanks a looot! You fixed my code.. I did not think of the 0 indexing for some reason when I was assigning the aux_list's array size. Neither did I think of the 2nd 'for loop's bounds' properly... very much appreciate it! – Sherzod Abdujabborov Dec 14 '17 at 19:51
  • @SherzodAbdujabborov glad it helped. Can you please vote and then accept my answer, so we can move this to the 'solved' list. Thanks! – curiouskiwi Dec 15 '17 at 0:01

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .