Reputation: 15
there is something that is troubling me, and I really can't find any answer through the internet (or at least i do not know how to search for it). I always thought that when declaring a size of a matrix as SIZE, the first element of the matrix is 0 and the last is SIZE-1. However, when compiling this:
#include<cstdio>
#include<cstdlib>
int main()
{
double *r;
r = new double[10];
double dr=0.1;
for(int i=0;i<=10;i++) r[i]=(double)i*dr;
for(int i=0;i<=10;i++) printf("%lf\n",r[i]);
delete [] r; r=0;
return 0;
}
no error is notified (i have tried this with 3 compilers so far gnu,dev and c-free), and even when I run the exe no error occurs. the results are:
0.000000
0.100000
0.200000
0.300000
0.400000
0.500000
0.600000
0.700000
0.800000
0.900000
1.000000---> element SIZE, which means 11, while I have declared 10 elements.
So, the question is: how is this possible?!?!!? here are the results when printing adresses:
006E0F88
006E0F90
006E0F98
006E0FA0
006E0FA8
006E0FB0
006E0FB8
006E0FC0
006E0FC8
006E0FD0
006E0FD8---> 11th element
thank you in advance.
Upvotes: 0
Views: 111
Reputation: 25695
your loop that goes from 0
to <=10
will access/print 11 elements.
This is UB. Accessing beyond your array boundaries is UB.
This should fix your code:
#include<cstdio>
#include<cstdlib>
int main()
{
double *r;
r = new double[10];
double dr=0.1;
for(int i=0;i<10;i++) r[i]=(double)i*dr;
for(int i=0;i<10;i++) printf("%lf\n",r[i]);
delete [] r; r=0;
return 0;
}
Your code has no syntax errors and no unresolved references, so the compiler will trust the programmer and let this UB pass. LINT
tool can probably catch this mistake, not sure.
Upvotes: 0
Reputation: 114461
In C and C++ it's very important to understand the concept of "undefined behavior".
The main assumption in those two languages is that the programmers make no error. They will never write past an array, they will never delete an object twice, they will never make a computation on signed integers to overflow and so on.
This means that the code generated by the compiler and the standard library is allowed to ignore such a possibility, and whatever happens happens.
May be your code will get a segfault when doing bad things (i.e. the OS itself will block a nonsense operation), but this only happens when you're lucky. In most of the cases nothing happens. To say it better nothing evident happens... but one million executed instructions later may be some perfectly valid code will behave crazily.
It's quite common in C and C++ that the code that triggers the segfault is just the innocent victim of some mistake that happened long ago.
So when coding in C and C++ just remember to never make a mistake ;-)
Upvotes: 3
Reputation: 227390
You are right that the indices of an array of size N
range from 0
to N-1
inclusive.
You are invoking undefined behaviour by accessing an array beyond its bounds. This is not a compilation error, but running such code will have unpredictable results.
Upvotes: 4