c++指针指向的内存问题
阿神
阿神 2017-04-17 13:50:12
0
2
586
#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不是指向的一个大小的内存吗?

阿神
阿神

闭关修行中......

répondre à tous(2)
伊谢尔伦

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

小葫芦

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

Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!