Home  >  Q&A  >  body text

c++指针指向的内存问题

#include <iostream>
#include <cstring>
#include <string>

using namespace std;

int main()
{

    int* str = new int[1];
    str[2] = 1;
    cout << str[2] << endl;
    return 0;
}

为什么这段代码可以正常运行哦?str不是指向的一个大小的内存吗?

阿神阿神2765 days ago626

reply all(2)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-17 13:52:12

    The array identifier of C does not contain the information of the array length, but only the address information, so the language itself cannot check it and can only be checked by the compiler. Early C language compilers did not check array out-of-bounds. , can only be checked and ensured by the programmer himself. In addition, in the early CRT functions, there was no out-of-bounds check on string pointers or arrays, which required programmers to ensure sufficient space. Therefore, there was a safe CRT function version provided by Microsoft after VS2005. Even if it goes out of bounds, it can be compiled normally. Try to expand the range and output the address at the same time. It can be seen that the out-of-bounds address is indeed accessed

    #include <iostream>
    #include <cstring>
    #include <string>
    
    using namespace std;
    
    int main()
    {
        int* str = new int[1];
        str[10000] = 1;
        cout << str << endl;
        cout << &str[10000] << endl;
        cout << str[10000] << endl;
        return 0;
    }

    0x100500000
    0x100509c40
    1
    Program ended with exit code: 0

    reply
    0
  • 高洛峰

    高洛峰2017-04-17 13:52:12

    It’s not that there are no problems, it just happens that there are no errors.
    You visited a space that doesn't belong to you, and no one happens to be using that space, so it seems fine.

    reply
    0
  • Cancelreply