cruelcore1
cruelcore1

Reputation: 578

Stack allocation in c++ for large sizes

I'm trying to load a whole lot of primitives using Direct3D 9, so I need to pass a large array of struct to virtual buffer. But if I do it with malloc(), my sizeof() function returns a wrong value (always 4). And if I typically allocate stack memory (array[number]), stack can overflow because of number of elements. Is there any alternative to it? How do I allocate stack memory that can load as much data?

P.S. I'm not gonna draw them all to the screen, but I still need their vertex information.

Upvotes: 0

Views: 116

Answers (4)

TimDave
TimDave

Reputation: 652

Your best option may be to allocate a std::vector dynamically and using a smart pointer.

std::shared_ptr< std::vector< your data type> > vertices( new std::vector( number );

Now you don't overflow the stack, all relevant housekeeping is done by std::vector and std::shared_ptr, and most importantly memory will get deleted.

Upvotes: 0

Digital_Reality
Digital_Reality

Reputation: 4738

Yes with malloc() and then using sizeof() will give you 4. That's the pointer size.

If you are just wondering how to fill your values in ptr then refer code below:

int numOfItems = 10;
int* pArr = (malloc(sizeof(int)*numOfItems);
for (int i=0;i<numOfItems;i++)
    pArr[i] = i+1;

Upvotes: 0

RichardPlunkett
RichardPlunkett

Reputation: 2988

If you called malloc, you called it with the size of the amount of space you wanted. If you want to know later on how big the allocation is, you need to keep that information around yourself.

Since your using C++, you could useIf you called malloc, you called it with the size of the amount of space you wanted. If you want to know later on how big the allocation is, you need to keep that information around yourself.

If that's too much trouble, since your using C++, you could use a <vector> or similar, which will track its own size. a vector or similar, which will track its own size.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409364

When used with a pointer, the sizeof operator returns the size of the pointer and not what it points to.

When you allocate memory dynamically (in C++ use new instead of malloc) you need to keep track of the amount of entries yourself. Or better yet, use e.g. std::vector.

Upvotes: 1

Related Questions