简体   繁体   中英

Write two functions to allocate and deallocate int array in C++ in the interview

I was asked to write two functions to allocate and deallocate int array in C++.

int* allocate(int size){
    return new int[size];
}

void deallocate(int *pt){
    delete pt;
    pt = NULL;
}

I came up with two functions as above.

Does anyone know is there better way to write functions to allocate/deallocate int array in C++?

I doubt there is a better way

It's not about better way or not, it's about correctness .

Use

delete [] pt;

since pt is an array !


Moreover, as thorsan suggested, you set pt to NULL , but that won't be visible outside of deallocate() , see for yourself:

#include <iostream>

using namespace std;

int* allocate(int size) {
    return new int[size];
}

void deallocate(int *pt) {
    delete [] pt;
    pt = NULL;
}

int main() {
        int* pt = allocate(5);
        deallocate(pt);
        cout << (pt == NULL ? "NULL" : "not NULL") << endl;
        return 0;
}

Output:

gsamaras@pythagoras:~$ g++ -Wall main.cpp 
gsamaras@pythagoras:~$ ./a.out 
not NULL

To avoid that, simply pass a reference , like this:

void good_deallocate(int*& pt) {
        delete [] pt;
        pt = NULL;
}

You could also check if the allocation was successful in your first function, like this:

int* good_allocate(int size) {
        try {
                return new int[size];
        }
        catch(std::bad_alloc&) {
                cerr << "shit\n";
                return NULL;
        }
        // OR as Dietmar Kühl suggested
        /*
        if (int* rc = new(std::nothrow) int[size]) {
                return rc; 
        } else {
                // handle error
        }
        */
}

inspired from How to check memory allocation failures with new operator?

if (int* rc = new(std::nothrow) int[size]) {
        return rc; 
} else {
        cout << "New failed, unable to allocate" << object_name << 
                ", size needed:" << sizeof( int ) * size << "." << endl;
        exit..., return... whatever, just don't use rc.
}

A lot of the comments (here and elsewhere) are about "why bother to handle?" Your program can't work, new/alloc errors don't happen on today's big (virtual) machines, etc. Think about how a program with an undetected 'new' error (or any error, for that matter) fails. For 'new', sometime later, you usually see an access violation. It may, or may not, be associated to the original failing statement/variable(s).

Now, pretend you are a user running this program (that, probably, you did not write). I usually see: "Access violation... core dumped" (or similar)? I want to see: "New failed, unable to allocate 'fluff', size = 24GB. Program terminated."

In the first example, the user calls the developer (at 2am, because these are always critical errors at worst possible time), and a major debugging effort ensues. Time to solve: hours? Days? In the second case, the user says "24GB? What the heck? Check the input - oh, oops, typo, I meant to say 24KB. Let me fix that." Time to solve: minutes. No call, no frustration.

Good diagnostics that the user can understand prevent [emergency] phone calls! Note, for example, even though I am allocating 'int's, that I included the logical object name , which hopefully means something to the user, and will aid him in fixing his problem. (Ummm, in case it need be said, emit the diagnostic at whatever level appropriate, just produce it and make it useful; it IS worth the effort.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM