why is this not giving error when I compile?
using namespace std;
int *a = new int;
// int a; // even this is not giving error
a = 0;
a = 1;
a = 2;
a = 3;
a = 4;
can someone explain why this is happening.
Thanks in advance.)
Because undefined behavior == anything can happen. You’re unlucky that it doesn’t crash, this sort of behavior can potentially hide bugs.
Declaring two variables called
a certainly is an error; if your compiler accepts that, then it’s broken. I assume you mean that you still don’t get an error if you replace one declaration with the other.
Array access is not range-checked. At compile time, the size of an array is often not known, and the language does not require a check even when it is. At run time, a check would degrade performance, which would go against the C++ philosophy of not paying for something you don’t need. So access beyond the end of an array gives undefined behaviour, and it’s up to the programmer to make sure it doesn’t happen.
Sometimes, an invalid access will cause a segmentation fault, but this is not guaranteed. Typically, memory protection is only applied to whole pages of memory, with a typical page size of a few kilobytes. Any access within a page of valid memory will not be caught. There’s a good chance that the memory you access contains some other program variable, or part of the call stack, so writing there could affect the program’s behaviour in just about any way you can imagine.
If you want to be safe, you could use
std::vector, and only access its elements using its
at() function. This will check the index, and throw an exception if it’s out of range. It will also manage memory allocation for you, fixing the memory leak in your example.
I’m guessing you’re coming from Java or a Java-like language where once you step out of the boundary of an array, you get the “array index out of bounds” exception.
Well, C expects more from you; it saves up the space you ask for, but it doesn’t check to see if you’re going outside the boundary of that saved up space. Once you do that as mentioned above, the program has that dreaded undefined behavior.
And remember for the future that if you have a bug in your program and you can’t seem to find it, and when you go over the code/debug it, everything seems OK, there is a good chance you’re “out of bounds” and accessing an unallocated place.
compilers with good code analysis would certainly warn on that code referencing beyond your array allocation. forgetting the multiple a declaration, if you ran it, it may or may not fault (undefined behavior as others have said). if, for example, you got a 4KB page of heap (in processor address space), if you don’t write outside of that page, you won’t get a fault from the processor. upon delete of the array, if you had done it, and depending on the heap implementation, the heap might detect that it is corrupted.