Accessing unallocated memory C++

前端 未结 6 1769
独厮守ぢ
独厮守ぢ 2020-12-11 20:06

I am having this piece of code:

try
{
    int* myTestArray = new int[2];

    myTestArray[4] = 54;

    cout << \"Should throw ex \"  << myTestAr         


        
6条回答
  •  有刺的猬
    2020-12-11 20:16

    There is an unstated, and incorrect, assumptions here. That assumption is that C++ actually gives a damn about what you do with memory. C++, like its C ancestor, has a completely unchecked model of memory. What you have here is classically called a buffer overflow, and is a source of innumerable bugs including some horrible security flaws.

    Here's what your code really says:

    • myTestArray is the name of a location in memory big enough to hold the address of an int.

    • Two ints worth of memory have been allocated on the heap for it. [And that addreress is put into the location myTestArray. Doesn't matter, but that probably makes it clearer.] (Along with probably 16 bytes of overhead, but we don't care about that now.)

    • you then are sticking the value 54 into the memory location 4 ints from the address contained in myTestArray.

    • looking at that location, adding 1 and printing the result.

    You are demonstrating that C(++) indeed just doesn't care.

    Now, under most conditions the underlying memory management and run time system won't let you get away with it; you will violate it's assumptions and get a segmentation error or something similar. But in this case, you are not hitting a boundary yet, most likely because you're piddling on the data structure that malloc is using under the covers to manage the heap. You're getting away with it because nothing is happening with the heap for the rest of the program. But for a real good time, write a little loop that does this code, freeing myTestArray and reallocating it. I'd lay long odds it won't run for more than 10 iterations before the program blows up, and might not make two.

提交回复
热议问题