Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C++ Dynamic Memory

C++ Dynamic Memory

Understanding how dynamic memory works in C++ is essential to becoming a qualified C++ programmer. The memory in a C++ program is divided into two parts:

Often, you cannot predict in advance how much memory is needed to store specific information in a defined variable; the required memory size can only be determined at runtime.

In C++, you can use a special operator to allocate heap memory at runtime for a variable of a given type, which returns the address of the allocated space. This operator is the new new operator.

If you no longer need the dynamically allocated memory, you can use the delete delete operator to free the memory previously allocated by the new operator.

new and delete Operators

The following is the general syntax for using the new operator to dynamically allocate memory for any data type:



new data-type;

Here,data-type can be any built-in data type including arrays, or any user-defined data type including classes or structures. Let's first look at built-in data types. For example, we can define a pointer to type double and then request memory, which is allocated at execution time. We can use new the new operator to do this:

double

pvalue

=

NULL

;

// Pointer initialized to null

pvalue

=

new

double

;

// Request memory for the variable

If the free store is exhausted, memory allocation may fail. Therefore it is recommended to check whether the new operator returns a NULL pointer and take appropriate action:

double

pvalue

=

NULL

;

if

(

!

(

pvalue

=

new

double

)

)

{

cout

<<

"

Error: out of memory.

"

<<

endl

;

exit

(

1

)

;

}

malloc() The malloc() function existed in C and still exists in C++, but its use is discouraged. Compared with malloc(), the main advantage of new is that it not only allocates memory but also creates the object.

At any time, when you think a dynamically allocated variable is no longer needed, you can use the delete operator to free the memory it occupies, as shown below:



delete pvalue;        // 释放 pvalue 所指向的内存

The example below uses the concepts above to demonstrate how to use the new and delete operators:

Example

#include

<

iostream

using

namespace

std

;

int

main

(

)

{

double

pvalue

=

NULL

;

// Pointer initialized to null

pvalue

=

new

double

;

// Request memory for the variable

pvalue

=

29494

.99

;

// Store a value at the allocated address

cout

<<

"

Value of pvalue :

"

<< *

pvalue

<<

endl

;

delete

pvalue

;

// Free memory

return

0

;

}

When the code above is compiled and executed, it produces the following result:



Value of pvalue : 29495

Dynamic Memory Allocation for Arrays

Suppose we want to allocate memory for a character array (a string of 20 characters); we can use the syntax from the example above to dynamically allocate memory for the array, as shown below:



char* pvalue  = NULL;   // 初始化为 null 的指针

pvalue  = new char[20]; // 为变量请求内存

To delete the array we just created, the statement is:



delete [] pvalue;        // 删除 pvalue 所指向的数组

The following is the general syntax of the new operator for allocating memory for multi-dimensional arrays:

One-dimensional array

// Dynamic allocation, array length m

int

array

=

new

int

[

m

]

;

// Free memory

delete

[

]

array

;

Two-dimensional array

int

**

array

;

// Assume the first dimension has length m and the second dimension length n

// Dynamically allocate space

array

=

new

int

[

m

]

;

for

(

int

i

=

0

;

i

<

m

;

i

++

)

{

array

[

i

]

=

new

int

[

n

]

;

}

// Free

for

(

int

i

=

0

;

i

<

m

;

i

++

)

{

delete

[

]

array

[

i

]

;

}

delete

[

]

array

;

2D array example test:

Example

#include

<

iostream

using

namespace

std

;

int

main

(

)

{

int

**

p

;

int

i

,

j

;

//p[4][8]

// Start allocating a 4-row, 8-column 2D array

p

=

new

int

[

4

]

;

for

(

i

=

0

;

i

<

4

;

i

++

)

{

p

[

i

]

=

new

int

[

8

]

;

}

for

(

i

=

0

;

i

<

4

;

i

++

)

{

for

(

j

=

0

;

j

<

8

;

j

++

)

{

p

[

i

]

[

j

]

=

j

i

;

}

}

// Print data

for

(

i

=

0

;

i

<

4

;

i

++

)

{

for

(

j

=

0

;

j

<

8

;

j

++

)

{

if

(

j

==

0

)

cout

<<

endl

;

cout

<<

p

[

i

]

[

j

]

<<

"

\

t

"

;

}

}

// Start freeing the allocated heap

for

(

i

=

0

;

i

<

4

;

i

++

)

{

delete

[

]

p

[

i

]

;

}

delete

[

]

p

;

return

0

;

}

Three-dimensional array

int


array

;

// Assume the first dimension is m, the second is n, and the third is h

// Dynamically allocate space

array

=

new

int

**

[

m

]

;

for

(

int

i

=

0

;

i

<

m

;

i

++

)

{

array

[

i

]

=

new

int

[

n

]

;

for

(

int

j

=

0

;

j

<

n

;

j

++

)

{

array

[

i

]

[

j

]

=

new

int

[

h

]

;

}

}

// Free

for

(

int

i

=

0

;

i

<

m

;

i

++

)

{

for

(

int

j

=

0

;

j

<

n

;

j

++

)

{

delete

[

]

array

[

i

]

[

j

]

;

}

delete

[

]

array

[

i

]

;

}

delete

[

]

array

;

3D array example test:

Example

#include

<

iostream

using

namespace

std

;

int

main

(

)

{

int

i

,

j

,

k

;

// p[2][3][4]

int


p

;

p

=

new

int

**

[

2

]

;

for

(

i

=

0

;

i

<

2

;

i

++

)

{

p

[

i

]

=

new

int

[

3

]

;

for

(

j

=

0

;

j

<

3

;

j

++

)

p

[

i

]

[

j

]

=

new

int

[

4

]

;

}

// Output p[i][j][k] 3D data

for

(

i

=

0

;

i

<

2

;

i

++

)

{

for

(

j

=

0

;

j

<

3

;

j

++

)

{

for

(

k

=

0

;

k

<

4

;

k

++

)

{

p

[

i

]

[

j

]

[

k

]

=

i

j

k

;

cout

<<

p

[

i

]

[

j

]

[

k

]

<<

"

"

;

}

cout

<<

endl

;

}

cout

<<

endl

;

}

// Free memory

for

(

i

=

0

;

i

<

2

;

i

++

)

{

for

(

j

=

0

;

j

<

3

;

j

++

)

{

delete

[

]

p

[

i

]

[

j

]

;

}

}

for

(

i

=

0

;

i

<

2

;

i

++

)

{

delete

[

]

p

[

i

]

;

}

delete

[

]

p

;

return

0

;

}


Dynamic Memory Allocation for Objects

Objects are no different from simple data types. For example, see the code below, where we use an array of objects to clarify this concept:

Example

#include

<

iostream

using

namespace

std

;

class

Box

{

public

:

Box

(

)

{

cout

<<

"

Constructor called!

"

<<

endl

;

}

~

Box

(

)

{

cout

<<

"

Destructor called!

"

<<

endl

;

}

}

;

int

main

(

)

{

Box

myBoxArray

=

new

Box

[

4

]

;

delete

[

]

myBoxArray

;

// Delete the array

return

0

;

}

If memory is allocated for an array containing four Box objects, the constructor will be called 4 times; similarly, when these objects are deleted, the destructor will also be called the same number of times (4).

When the code above is compiled and executed, it produces the following result:



调用构造函数!

调用构造函数!

调用构造函数!

调用构造函数!

调用析构函数!

调用析构函数!

调用析构函数!

调用析构函数!