1,435 views
1 votes
1 votes
In C, An array is declared as int a[5];

What will be the result if i execute this statement

a[5] = 0;

 

A. Segmentation fault

B. All elements will be initialized to 0.

C. A 0 will be stored outside array boundary

D. C does boundary check and a compiler error will be displayed

2 Answers

Best answer
2 votes
2 votes

Option B is wrong. For this we must do

int A[5] = {0};

as part of initialization.

Option D is also wrong - C compiler don't do this - it sometimes warn though. Not all array out of bound cannot be checked also by the C compiler.

When we declare int A[5], that means size of array A[] is 5, which can store values in memory locations from A to A+4. Now, when we want to store some value outside of this range, two things can happen:

  1. Invalid memory access error can be thrown - often segmentation fault - option A
  2. Memory might have been allocated by compiler for someother purpose and so there won't be any error. -option C.

So, correct answer should be "None of these" as sometimes is not always.

PS: These kind of questions are never asked for GATE. Ofcourse with no correct answer, it should not be asked anywhere but in GATE questions related to errors are quite rare.

selected by
0 votes
0 votes
It will result in segmentation as it cannot access the memory reference.

Related questions

0 votes
0 votes
1 answer
3