Dynamic Memory Allocation
Dynamic Memory Allocation
3/03/11
Operator new
2000
char*
ptr;
??? 5000
ptr
Example of new
// Precondition: n is a positive integer // Postcondition: computes and prints out the first n // elements of the Fibonacci sequence void fibonacci(int n){ int *x = new int [n]; // creation of a dynamic array x[0]=1; x[1]=1; for (int i=2;i<n;i++) x[i]=x[i-1]+x[i-2]; cout<<"The Fibonacci sequence of "<<n<<" values are:\n"; for (int i=0;i<n;i++) cout<<"x["<<i<<"]="<<x[i]<<endl; }
Semantics of new
For type *pointer = new type; :
The system allocates dynamically (during execution) a chunk of memory large enough to hold data of the specified type, and returns a pointer pointing to the address of that chunk. This pointer is stored in the user-provided pointervariable pointer.
Operator delete
char* ptr;
2000 5000 ???
ptr
5000
B NOTE: delete deallocates the memory pointed to by ptr
delete
Example
char *ptr ; ptr = new char[ 5 ]; strcpy( ptr, Bye ); ptr[ 0 ] = u; 6000
B y e \0 u // deallocates the array pointed to by ptr // ptr itself is not deallocated // the value of ptr becomes undefined