简体   繁体   English

在面试中编写两个函数来分配和释放C ++中的int数组

[英]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++. 我被要求编写两个函数来在C ++中分配和释放int数组。

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++? 有谁知道有更好的方法来编写在C ++中分配/解除分配 int数组的函数?

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 ! 因为pt 是一个数组


Moreover, as thorsan suggested, you set pt to NULL , but that won't be visible outside of deallocate() , see for yourself: 此外,正如thorsan所建议的那样,你将pt设置为NULL ,但是在deallocate()之外不可见,请亲自看看:

#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. 你的程序无法工作,新的/ alloc错误不会发生在今天的大型(虚拟)机器上等等。想想一个程序如何检测到未检测到的“新”错误(或任何错误)。 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." 我想看看:“新的失败,无法分配'绒毛',大小= 24GB。程序终止。”

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. 在第一个示例中,用户调用开发人员(凌晨2点,因为这些在最糟糕的时间始终是关键错误),并且随后会进行大量的调试工作。 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." 在第二种情况下,用户说“24GB?哎呀?检查输入 - 哦,哎呀,错字,我的意思是24KB。让我解决这个问题。” 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. 请注意,例如,即使我正在分配'int',我也包含逻辑对象名称 ,这有望对用户有所帮助,并有助于他解决问题。 (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.) (嗯,如果需要说的话,在适当的任何级别发出诊断,只需生产并使其有用;值得努力。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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