Dynamic memory in C++

Hello,

I've been reading the C++ tutorial on this site, and I have a question about dynamic memory. It says that dynamic memory can be used where we want to allocate a runtime-decided amount of memory. However (let's suppose that I want to allocate an array whose size if defined during runtime), this can be easily done without the use of "new":
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

int main() {
    cout<<"Give the array index number"<<endl;
    int x;
    cin>>x;
    int array[x];
    for (int i=0;i<=(x-1);i++) {
        array[i]=i+1;
        }
    cout<<"Size of array:"<<endl<<sizeof(array);
    cin.get();
    cin.get();
    for (int i=0;i<=(x-1);i++) {
        cout<<array[i]<<"\t";
        }
    cin.get();
}

This works perfectly on my compiler (Bloodshed dev c++), and the array's size if defined during runtime. So is it just my compiler that this will work on, or where am I wrong? OR does it in fact use the "new" operator while I haven't used it anywhere in my code?

Thanks
I think it's your compiler. Mine (Borland command line compiler) gives the error "constant expression required in function main()" at line 8. In other words, I can't say "int array[x]" unless x is a constant.
Thanks!

One last thing; How can the program know how many memory cells to free up when I'm using the delete[] operator? Since I do not specify any number beween "[" and "]" how can it guess that, given only one pointer?
I believe that the
int array[x];
is valid C++, but I'm not sure... Like magicalblender mentioned though, such a feature is not well-supported...

The problem is that it is not persistent memory. For example, if I were to say:
1
2
3
4
int *make_array( unsigned size ) {
  int array[ size ];
  return array;
  }

This would return a garbage pointer, since the array is automatically freed (just as every other local variable) when the function terminates.

Dynamic memory usually refers to _persistent_ global memory (i.e. the heap).

The way the heap is managed behind the scenes is left to the implementation, but typically there is an allocation record created that tracks information about the size of the user-accessible area. Hence, when delete[] is called, it knows to look to see exactly how much memory to free.

Hope this helps.
Topic archived. No new replies allowed.