使用未分配的内存没有错误? [英] using unallocated memory without error?

查看:148
本文介绍了使用未分配的内存没有错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这样工作?

#include <iostream>
using namespace std;

int main() {
    float* tab[3];

    int i = 0;
    while(i < 3) {
        tab[i] = new float[3-i];
        i++;
    }

    cout << tab[2][7] << endl;
    tab[2][7] = 6.87;
    cout << tab[2][7] << endl;

    i = 0;
    while(i < 3)
        delete[] tab[i];
}

而这不是?

#include <iostream>
using namespace std;

int main() {
    float* tab = new float[3];

    cout << tab[7] << endl;
    tab[7] = 6.87;
    cout << tab[7] << endl;

    delete[] tab;
}

我试过两个程序在Win XP与MS VS 2008,第一个运行没有任何错误。第二个弹出一些错误窗口,但我不记得它,不能再现(目前没有访问Windows)。

I tried both programs on Win XP with MS VS 2008, both compiled without errors and the first one ran without any errors. The second made pop up some error window, however I can't remember it and can't reproduce (no access to Windows at the moment).

我也试过他们在Linux上(Kubuntu 10.10与预编译的内核包版本2.6.35.23.25)与g ++和编译和运行没有任何错误。

I tried them also on Linux (Kubuntu 10.10 with precompiled kernel package version 2.6.35.23.25) with g++ and both compile and run without any errors.

为什么?

我知道它应该(幸运的是,没有错误)编译没有错误,但我认为它不应该运行没有他们...为什么第二个例子在Windows上而不是在Linux上的错误?

I know it should (and, luckily, does) compile without errors, but I thought it shouldn't run without them... And why the second example makes errors on Windows and not on Linux?

推荐答案

使用未分配的内存会导致未定义的行为。当你在同一个系统和编译器上这样做时,你可能没有期望会发生什么,更不用说在硬件和编译器的不同组合上。

Use of unallocated memory results in undefined behaviour. You can have no expectations of what will happen when you do this even on the same system and compiler, let alone across different combinations of hardware and compiler.

程序可能会立即崩溃,它可能会工作一段时间,然后失败,它甚至可能看起来工作完美。

The program might crash immediately, it might work for a while and then fail later, it might even appear to work perfectly.

但是,访问您不拥有的内存总是一个编程错误。不要认为正确操作的外观是它有时工作,认为它是我真的不幸运,我的错误不快速显示。

Accessing memory you don't own is always a programming error, though. Don't think of the appearance of correct operation as "it sometimes works", think of it as "I got really unlucky and my bug does not show up quickly".

这篇关于使用未分配的内存没有错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆