1

I'm using C++11. I realised I can do this and allocate on stack:

void someclasS::somefn(int naz) {
    Ipp32f absValues[naz] // <--naz is dynamic
    //.....more code
    //.....
}

I thought I wasn’t supposed to be able to do this? Previously I was doing this:

std::unique_ptr<Ipp32f[]> absValues(new Ipp32f[naz]); 
// when need to pass pointer have to use absValues.get()

To avoid having to delete the memory.

I would like very much to do the former if possible as it looks neater. But what are the consequences of doing so, if any?

Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82
lppier
  • 1,927
  • 3
  • 24
  • 62

2 Answers2

3

It works because the compiler accepts VLAs even if they're not standard in C++.

The normal way is to use an std::vector as Humam Helfawi says.

The rationale of not allowing VLAs is that either you are sure that there is no stack overflow because there is a cap on the size (and in this case just allocate that size) or the quantity is unlimited and you indeed should allocate it on the free store as this allows better handling of out of memory conditions.

Community
  • 1
  • 1
6502
  • 112,025
  • 15
  • 165
  • 265
  • What is the cap that you speak of? How much? – lppier Jan 20 '16 at 08:03
  • Hi.. I've read that it's typically around 4mb... that's pretty small. – lppier Jan 21 '16 at 01:12
  • @lppier: what I meant is that if you know for sure that say `n <= 100` then allocating an `int[n]` on the stack would be reasonably safe, but in that case you can just allocate `int[100]` instead and there is no need of VLAs. If on the other hand there is no upper limit on what `n` can get then probably allocating `int[n]` on the stack is a bad idea because stack overflow is undefined behavior while memory exhausting on the free store is instead properly signaled. – 6502 Jan 21 '16 at 07:15
2

I would like very much to do the former if possible as it looks neater

Just use std::vector.

std::vector<Ipp32f> absValues(naz);

The result is contiguous if you have a function with this declaration:

ppsZero_32f(Ipp32f* ptr, int len);

You can pass your vector like this:

ppsZero_32f(absValues.data(),absValues.size());
Humam Helfawi
  • 19,566
  • 15
  • 85
  • 160