它是安全返回VLA? [英] Is it safe to return a VLA?

查看:104
本文介绍了它是安全返回VLA?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下code使用堆:

 的char *的getResult(INT长度){
    字符*结果=新的char [长度]
    //填写结果...
    返回结果;
}诠释主要(无效){
    字符*结果=的getResult(100);
    // 做一点事...
    删除的结果;
}

所以结果在某处被删除,preferably由业主。

下code,从我的理解中,使用名为VLA的延伸,这是C99的一部分,而不是C ++标准的一部分(但GCC的支持,以及其它编译器):

 的char *的getResult(INT长度){
    焦炭结果[长度]
    //填写结果...
    返回结果;
}诠释主要(无效){
    字符*结果=的getResult(100);
    // 做一点事...
}

我在假设结果在这种情况下仍然在栈中分配是否正确?

结果拷贝,或者是垃圾内存的引用?是上面code安全吗?


解决方案

  

我是在假设结果在这种情况下,在堆栈上仍被分配校正


正确的。 VLA具有自动存储时间。


  

时造成的副本,或者是垃圾内存的引用?是上面code安全吗?


在code是不是安全的。通过的getResult 返回的地址是无效的地址。解引用指针调用未定义的行为。

The following code uses the heap:

char* getResult(int length) {
    char* result = new char[length];
    // Fill result...
    return result;
}

int main(void) {
    char* result = getResult(100);
    // Do something...
    delete result;
}

So result has to be deleted somewhere, preferably by the owner.

The code below, from what I understand, use an extension called VLA, which is part of C99, and not part of the C++ standard (but supported by GCC, and other compilers):

char* getResult(int length) {
    char result[length];
    // Fill result...
    return result;
}

int main(void) {
    char* result = getResult(100);
    // Do something...
}

Am I correct in assuming that result is still allocated on the stack in this case?

Is result a copy, or is it a reference to garbage memory? Is the above code safe?

解决方案

Am I correct in assuming that result is still allocated on the stack in this case?

Correct. VLA have automatic storage duration.

Is result a copy, or is it a reference to garbage memory? Is the above code safe?

The code is not safe. The address returned by getResult is an invalid address. Dereferencing the pointer invokes undefined behavior.

这篇关于它是安全返回VLA?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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