Thanks for your suggestion!
But I have tried this code, causing no RE. Why?
In general, an invalid memory access has unpredictable results. Many things could happen. Your program could crash (in many different ways), it may not crash and produce crazy results, it may not crash and produce results that seem okay... who knows.
I find two strange things about the code you have posted, one is that you didn't use any include
directives, where you should at least have used cstdio or stdio.h. Another is that you used gcc instead of g++ to compile a program that seems to be written in C++ (because of the new
operator). I wonder how you managed to get that compiled... although I'm not familiar with Ubuntu and their setup may allow such strange things.
After a few minor changes, when I compile your code in my laptop, it prints:
It's probably not crashing because, although n is not a valid position in the segment of memory you reserved with new
, it probably doesn't go outside of the block of memory assigned to your program, so C/C++ simply keeps going. The tacit assumption, if you could call it that, made by the language is that you know what you're doing, and doesn't stop you from doing it. It's only when you play with things that are clearly outside of your sandbox, that the OS comes and says "hey! you can't do that".
For example, try this:
Code: Select all
printf( "First test.\n" );
printf( "%d\n", n[ 1 << 20 ] ); /* Does this */
printf( "Last test.\n" );
Since it tries to access a memory location much farther away from the block of memory of your variable, it's more likely to trigger the response you wanted.