Question

int length = 5;
int hi[length];

vs

int length = 5;
int *hi = new int[length];

I was taught compilers complain in C whenever you try to statically allocate arrays w/ size that's not constant. So if you ever needed array of unknown size, you needed to dynamically allocate memory. However, now that there are compilers that allow the first example, what exactly are they doing? Are they still going in the data-segment, or are they not going on the heap? If they're going on the heap, then what is the difference between the examples, and why would I still have to call delete[] on the 2nd example, but not the 1st example?

Was it helpful?

Solution

However, now that there are compilers that allow the first example, what exactly are they doing? Are they still going in the data-segment, or are they not going on the heap? If they're going on the heap, then what is the difference between the examples, and why would I still have to call delete[] on the 2nd example, but not the 1st example?

The first one is declaring a static variable (usually on the stack*) that will die at the end of the code block in which it is defined.

The second one is dynamically allocating a variable (usually on the heap*) which means that you are the one that can decide where to deallocate it with delete[] (and yes you should remember to do it).

The main difference between the two, in the array context, is that the second one can be easily resized by deallocating the memory it points (the previous array for example) and make it point to a new array still dynamically allocated.

int* arr = new int[5];
[...]
delete[] arr;
arr = new int[10];

Static arrays int hi[length] usually declare a const int* which shouldn't be modified instead. It is to say that C++ provides a complete set of containers that can / should be used instead of arrays.

[*] Note: The C++ standard doesn't specify where to allocate dynamic or static memory.

OTHER TIPS

Presumably your code

int length = 5;
int hi[length];

is at local scope, not file scope, as the latter wouldn't be legal.

Are they still going in the data-segment

They were never going in the data-segment; they go on the stack (in typical/common implementations; the language standard doesn't say where they go).

why would I still have to call delete[] on the 2nd example, but not the 1st example?

First, VLA's (variable length arrays like hi[length]) aren't legal in C++, so you couldn't call delete[]. But there's no need to call delete because hi goes out of scope at the end of the block it's in. An object or array allocated by new, OTOH, does not go out of scope until deleted. Only the pointer, hi, goes out of scope, but you may have assigned its value to another pointer that is still in scope.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top