Rui Dias
Rui Dias

Reputation: 13

Segmentation Fault if I don't say int i=0

void removeVowels(char* array){
  int i,j,v;
  i=0;

  char vowel[]={'a','e','i','o','u'};
  while(array[i]!='\0')
  {
    for(v=0;v<5;v++)
    {
      if (array[i]==vowel[v])
      {
          j=i;
          while(array[j]!='\0')
          {
            array[j]=array[j+1];
            j++;
          }
          i--;
          break;
      }
    }
    i++;
  }


}

in function removeVowels() if I don't include i=0; and just say int i; why does it give segmentation fault? Isn't it automatically 0?

Full code here

Upvotes: 1

Views: 118

Answers (3)

Rafaf Tahsin
Rafaf Tahsin

Reputation: 8626

If you declare int globally then it is initiated with the value 0. Otherwise it contains garbage value. You can try the following code.

#include<stdio.h>

int global;

int main()
{
    int local;
    printf("global = %d, local = %d\n", global, local);
    return 0;
}

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227608

Isn't it automatically 0?

No, it isn't. It i has automatic storage, so its default initialization leaves it uninitialized, holding an indeterminate value. To read from it before initializing it is undefined behaviour.

Upvotes: 4

Sourav Ghosh
Sourav Ghosh

Reputation: 134396

In your code, int i is an automatic local variable. If not initialized explicitly, the value held by that variable in indeterministic.

So, without explicit initialization, using (reading the value of ) i in any form, like array[i] invokes undefined behaviour, the side-effect being a segmentation fault.

Isn't it automatically 0?

No, variables with static storage class will get this "facility" of implicit initialization, not automatic local variables.

Upvotes: 0

Related Questions