Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Array question 1

Status
Not open for further replies.

aakafh

Programmer
Sep 21, 2011
1
IN
#include<stdio.h>
int main()
{
int arr[2]={10,9};
printf("%d\n",4[arr]);
return 0;
}

this is giving output 1,shoudn`t it give segmentation fault cause the array is of size 2 and we are printing the value of array cell with index 4.Plz reply asap.
 

> shoudn`t it give segmentation fault cause the array is of size 2
Array overruns are undefined behaviour, which basically means anything can happen, ranging from "hey, it worked" to "where are my OS installation disks?".


--
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
 
Nope; rhis one of the most common errors in C/C++ programming. You can over run the array boundaries, and you will get what is called undefined behavior. You might get a seg fault, but more likely you will just read a section of randomized memory. It depends where in the segment your array is situated. If it is located on the boundary of the segment and the overrun causes you to read past that boundary, and if the adjacent segment is locked for reading to the program, then yes, it will cause a seg fault. otherwise no.
 
trying to read from outside the boundaries is poor programming

trying to write outside the boundaries is a disaster waiting to happen ( what do you think causes most of the security notices)
not just where's my install disk but also where's my data & what happened to my bandwidth?

Mundus vult decipi decipiatur ergo.
 
Use good compilers (and never suppress warnings): for example, VC prints message on out of range index in
Code:
printf("%d\n",4[arr]);
(debug mode only;).
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top