Member function memory allocation stack or heap?

那年仲夏 提交于 2021-02-10 12:57:23

问题


I'm trying to allocate an array as follows:

class foo{
public:
    void func(){double arr[13][64][64][64];}
};

int main()
{
    foo* inst = new foo();
    inst->func();       
    return 0;
}

I was under the impression from answer such as: Does this type of memory get allocated on the heap or the stack? that the array arr would be placed on the heap (as the instance of the class is on the heap). This doesn't seem to be the case as I get a segmentation fault. If I change a's declaration to: double* arr = new double[13*64*64*64]; (and delete it properly) then everything's fine.

What's happening here?


回答1:


You are confusing member variables with variables declared inside a member function.

class Foo {
  public:
    int arr[13][64][64][64]; //Will be allocated in the same memory as the instance

    void func() {
      int arr2[13][64][64][64]; //Will always be allocated on the stack
    };
};

So if you have Foo* foo = new Foo() arr is allocated on the heap because the whole foo object is allocated on the heap. On the other hand Foo bar(); now arr is allocated on the stack because bar is allocated on the stack.

Calling either foo->func() or bar.func() will allocated the arr1 array on the stack.




回答2:


Would you expect the following function to allocate arr on the heap?

void free_func(foo * this_)
{
    double arr[13][64][64][64];
}

Of course you wouldn't. The function foo:func is no different, except that this is passed automatically. Whether this is on heap or not makes no difference.




回答3:


Array is allocated in func()'s stack frame, like it normally happens to local variables. I'm not sure though why would this code cause segfault. Unless to honor the name of this site.



来源:https://stackoverflow.com/questions/19492433/member-function-memory-allocation-stack-or-heap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!