1

I was wondering if accessing an array outside its boundary(line 2 in the following code sample) would ever produce an error?

int a[20];
int* ptr = &a[20]; // line 2
int count=20;
do
{
  ptr--;
  printf("%d",*ptr);
}while(--count!=0);
Tahlil
  • 2,680
  • 6
  • 43
  • 84
thunderbird
  • 2,715
  • 5
  • 27
  • 51

5 Answers5

5

According to C Traps and Pitfalls:

But how can it make sense to refer to an element that doesn't exist?
Fortunately we do not have to refer to this element, merely to its address, and that address does exist in every C implementation we have encountered. Moreover, ANSI C explicitly permits this usage: the address of the nonexistent element just past the end of an array may be taken and used for assignment and comparison purposes. Of course it is illegal actually to refer to that element!

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
2

Trying to access memory beyond the end of the array is undefined behavior. However, It is perfectly legal to have a pointer to point at one element beyond the end of the array. The distinction between pointing to a certain address and accessing it is important.

For example, you can use the following to find the size of an array arr

int size = (&arr)[1] - arr;
Arjun Sreedharan
  • 11,003
  • 2
  • 26
  • 34
1

Accessing memory address outside an array boundary may not crash the the process always. But certainly it will corrupt the address space if you modify the data. Also, sometime memory address outside an array boundary will really lie outside the process address space, that will result in seg-fault.
Anyway, this is a dangerous. It will introduce hard to narrow-down error. The memory corruption, or weird behavior of the program will manifest at some other place, and we will spend hours and hours finding the needle in the haystack.

Nipun Talukdar
  • 4,975
  • 6
  • 30
  • 42
1

Modifying the address past array boundary will never produce a compiler error, since C compiler doesn't treat it as error.
However on some machines if this address is not allowed to be accessed, you may get a Runtime Error (Seg Fault).

This is similar to writing to address 0 (NULL).

On a microprocessor/microcntroller/embedded devices on some architectures, you may be allowed to write at address 0, it is perfectly valid but on some other machines you may get SEGFAULT.

That is why this is also termed as undefined behavior.

0xF1
  • 6,046
  • 2
  • 27
  • 50
0

Your code does not access memory beyond the end of the array. so changes your code little. Count changed to 100 from 20

#include<stdio.h>

int main() {
int a[20];
int* ptr = &a[20]; // line 2
int count=100;
do
{
  ptr--;
  printf("%d",*ptr);
}while(--count!=0);
return 0;
}

see http://codepad.org/X8yqrnDC

NO at compilation it will not give any error.

But at run time it might get segmentation fault.

as per standard its undefined behavior

Jeegar Patel
  • 26,264
  • 51
  • 149
  • 222