>  Q&A  >  본문

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不是指向的一个大小的内存吗?

阿神阿神2714일 전585

모든 응답(2)나는 대답할 것이다

  • 伊谢尔伦

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

    C的数组标识符,里面并没有包含该数组长度的信息,只包含地址信息,所以语言本身无法检查,只能通过编译器检查,而早期的C语言编译器也不对数组越界进行检查,只能由程序员自己检查确保。以及在早期的CRT函数中也不对字符串指针或数组进行越界检查,都是要求程序员确保空间足够,因此也才也才有了在VS2005之后微软提供的安全的CRT函数版本。即使越界也能正常编译通过,试着扩大一下范围,同时输出地址,可以看出,确实是访问了越界的地址

    #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

    회신하다
    0
  • 高洛峰

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

    不是没有问题,只是恰好没出现错误而已。
    你访问了一个不属于你的空间,而那个空间恰好没人在使用,所以看起来没问题。

    회신하다
    0
  • 취소회신하다