2

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?

trincot
  • 317,000
  • 35
  • 244
  • 286
Jack
  • 115
  • 5
  • indirectly, the array would get allocated dynamically (because foo is dynamically allocated) - however, it's very unclear to me what you want to achieve with this unused variable in `foo`? – codeling Oct 21 '13 at 10:52
  • 1
    @nyarlathotep - Jack created a minimum working example to illustrate his problem. – David Hammen Oct 21 '13 at 10:55
  • 1
    @nyarlathotep: No it wouldn't. Like any local variable, it's automatic, i.e. on the stack (unless you specify `static` or `threadlocal`, but even then it won't be dynamic). Dynamically allocating an object only means that its members are on the heap. – Mike Seymour Oct 21 '13 at 10:55
  • ah, sure, the difference to the linked question being that it's in a method and not member of a class, right, like Hugo T's answer is pointing out? thanks for the correction – codeling Oct 21 '13 at 11:03

3 Answers3

6

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.

Hugo Tunius
  • 2,869
  • 24
  • 32
1

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.

avakar
  • 32,009
  • 9
  • 68
  • 103
1

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.

Michael Krelin - hacker
  • 138,757
  • 24
  • 193
  • 173