0

I dynamically allocated an array (unsigned int n might have been passed as a parameter in a function):

int * ar = new int [n];

When I'm done using it:

delete [] ar;

But, what happens when n = 0? Is allocate 0 ints the same as not allocating at all? In which case, do bad things happen when I call delete?

Fine Man
  • 455
  • 4
  • 17
  • 2
    https://stackoverflow.com/questions/1087042/c-new-int0-will-it-allocate-memory And you do allocate something (data for managing your allocation at least) - it's not the same as doing nothing. – deviantfan Aug 14 '17 at 19:59
  • @deviantfan -- My bad! I didn't find any duplicates because I was phrasing as "can you `delete` `0`", whereas your link phrased it as "can you `new` `0`" (in the end, it's kinda the same thing). Should I delete this Q? – Fine Man Aug 14 '17 at 20:11
  • Use std::vector! –  Aug 14 '17 at 20:19
  • @FineMan I don't think you can ... anyways, duplicates help at least for others finding this, then following the link. And you got a answer here too. No need to worry. – deviantfan Aug 14 '17 at 20:32
  • @deviantfan -- Good point. `:)` – Fine Man Aug 14 '17 at 20:33

1 Answers1

4

It's ok to new a zero-sized array, and to delete it. This is more of a convenience than anything, as it means you don't have to write separate conditions for the 0 case.