Member function memory allocation stack or heap?
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?
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.
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.
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.
上一篇: JQuery检查以查看是否显示Div
下一篇: 成员函数内存分配堆栈还是堆?