Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

c++ - using unallocated memory without error?

Why does that work?

#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];
}

while this one doesn't?

#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;
}

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).

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.

Why? Shouldn't there be any pop-ups with something like "Wrong access to unallocated memory"?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...