> it works for 100 elements too why?
Because works is really "works".
Never confuse "it works" with "bug free".
It's basically luck because you only call new once, and you never call delete. You trash the memory pool with your buffer overrun, but you typically only find out when the next call to new/delete comes along.
As soon as you start adding more allocations, and start freeing the memory after you're done, you're on a very slippery slope to disaster.
For example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include <iostream>
int main() {
int *x = new int[1];
for (int j = 0; j < 20; j++) {
x[j] = j;
}
int *y = new int[1];
for (int k = 0; k < 20; k++) {
std::cout << x[k] << std::endl;
}
delete [] x;
delete [] y;
return 0;
}
|
This produces garbage output, because the 2nd new claimed what should be it's by right.
Whereas this crashes and burns on exit, because the internal pool structure for the y pointer was trashed by overrunning x.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include <iostream>
int main() {
int *x = new int[1];
int *y = new int[1];
for (int j = 0; j < 20; j++) {
x[j] = j;
}
for (int k = 0; k < 20; k++) {
std::cout << x[k] << std::endl;
}
delete [] x;
delete [] y;
return 0;
}
|
> This above program give error in MS visual Studio, but work in other compiler, like CLang, GNC C++, Cmake etc.
Yes, that's a sure sign your code is wrong.
If all three compilers produce code that gives you the same result (actually 6 if you test both debug and release builds), then your code is in pretty good shape.