Izzo
Izzo

Reputation: 4928

How to detect if an object is made up primarily of stack or dynamic memory

I've currently been working with a library that potentially creates heavy weight objects. Specifically, I'm creating objects that are associated with wave files.

Now when creating an instance of a Wave Object (just as an example), is there a good way to determine where it is being allocated in memory?

For example, if I were to instantiate a std::vector in the stack, I know that some memory is allocated on the stack (i.e. header information) and the actual container data is created on the heap. So for the most part, I don't have to worry about a stack memory overflow. Although I still have the option to fully instantiate the object in heap.

But let's say I don't know about an objects implementation. Let's say I'm using a library that creates a massive array in the stack. This could potentially cause problems.

So my question: how do we know how 'heavy' an object is memory wise?

Upvotes: 0

Views: 74

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 473537

I'm going to assume that extra-standard methods of allocating stack memory are off the table (alloca and friends).

Given that, it's simple: take the sizeof the object.

C++ is a statically typed language, but its objects are also statically sized. Every type has a size that must be determinable at compile-time. Lots of C++ relies on this. So if you're concerned about some object taking up too much stack space, that could only be because the sizeof the object took up that space.

Note that this will not prevent issues where you call a function that itself uses lots of stack space. There's nothing you can do to detect that. But you can tell if the size of a given object will be "large" or not, by some arbitrary measurement.

Upvotes: 3

Related Questions