0
int position_of_largest(int * array, int size)
{
  int largest, i, largest_i;
  i = 0;
  largest_i = 0;
  while (i < size)
  {
    if (i == 0)
    {
      largest = array[0];
      largest_i = 0;
    }
    else
    {
      if (largest < array[i])
      {
        largest_i = i;
        largest = array[i];
      }
      i++;
    }
  }

  return largest_i;
}

This code is supposed to find the index of the highest element in the array and return it. There is a segmentation fault in this code, apparently, but I have no clue what it is! I have looked through the code many times and I don't see any problem. I am new to C, btw (which explains a lot). Thanks.

alk
  • 69,737
  • 10
  • 105
  • 255
  • segmentation fault is when you try to access un-allocated or un-authorized memory space.. i hope when you are calling the function `position_of_largest(int * array, int size)` you are sending a pointer to enough memory space ( size*4 bytes) to the `array` pointer – Haris Jan 16 '15 at 18:46
  • 2
    Can we see the call of the function? Also, `i++` never gets executed. – Igor Pejic Jan 16 '15 at 18:49
  • 1
    @haris: Sometimes. When you are on the right kind of machine and are unreasonably lucky. – Deduplicator Jan 16 '15 at 18:49
  • @Deduplicator what about unfortunately lucky? – Iharob Al Asimi Jan 16 '15 at 18:50
  • 1
    Regarding what a segmentation fault is: http://stackoverflow.com/q/2346806/694576 – alk Jan 16 '15 at 19:02

1 Answers1

3

It is not causing segmentation fault but this code goes to an infinite loop. It is because you place i++ in else block. It is never get incremented.

Place it outside the else block.

else { 
    if (largest < array[i]) {
        largest_i = i;
        largest = array[i];
    } 
}
i++; 
haccks
  • 104,019
  • 25
  • 176
  • 264