Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Suppose a dynamic variable were created as follows: char *p; p = new char; Assum

ID: 3704621 • Letter: S

Question

Suppose a dynamic variable were created as follows:

char *p;

p = new char;

Assuming that the value of the pointer variable p has not changed (so it still points to the same dynamic variable), how can you destroy this new dynamic variable and return the memory it uses to the freestore manager so that the memory can be reused to create other new dynamic variables?

Suppose your program contains code to create a dynamically allocated array as in
question above , and suppose the pointer variable entry has not had its (pointer) value
changed. Write code to destroy this dynamically allocated array and return the memory
it uses to the freestore manager.

Explanation / Answer

Solution :-

// C++ program to illustrate dynamic allocation and deallocation of memory using new and delete

#include <iostream>

using namespace std;

int main ()

{

int* p = NULL;// Pointer initialization to null

p = new int; // Request memory for the variable using new operator

if (!p) // checking p have value or not (It will return either true or false)

cout << "allocation of memory failed "; //Displaying the massage

else{

*p = 29; // Store value at allocated address

cout << "Value of p: " << *p << endl; //Displaying the value of p.

}

float *r = new float(75.25); //Request block of memory using new operator

cout << "Value of r: " << *r << endl; // Displaying the value of r.

int n = 5;//Request block of memory of size n

int *q = new int[n]; //creating array of 5 element.

if (!p)

cout << "allocation of memory failed ";//displaying the massage of failed memory

else

{

for (int i = 0; i < n; i++)

q[i] = i+1; //increment of value by 1

cout << "Value store in block of memory: "; //Displaying the massage

for (int i = 0; i < n; i++)

cout << q[i] << " ";//Displaying the value of array

}

delete p;//freed the allocated memory

delete r;// freed the allocated memory

delete[] q; // freed the block of allocated memory

return 0;

}

Output:

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote