Dynamic Memory
- What is the output of this program?
#include <iostream>
#include <cstdlib>
using namespace std;
class OperatorX
{
public:
void* operator new(size_t sz) throw (const char*)
{
void* ptr1 = malloc(sz);
if (ptr1 == 0)
throw "malloc() failed";
return ptr1;
}
void operator delete(void* ptr1)
{
cout << "Operator X :: delete(void*)" << endl;
free(ptr1);
}
};
class OperatorY
{
int filler[150];
public:
void operator delete(void* ptr1, size_t sz) throw (const char*)
{
cout << "Freeing " << sz << " bytes" << endl;
free(ptr1);
};
};
int main()
{
OperatorX* ptr1 = new OperatorX;
delete ptr1;
OperatorY* ptr2 = new OperatorY;
delete ptr2;
}
-
View Hint View Answer Discuss in Forum
NA
Correct Option: D
The memory value allocated for the program depends on compiler only.
- What type of class member is operator new?
-
View Hint View Answer Discuss in Forum
NA
Correct Option: C
static
- What is the output of this program?
#include <iostream>
#include <new>
using namespace std;
struct N
{
virtual ~N() { };
void operator delete(void* ptr1)
{
cout << "N :: operator delete" << endl;
}
};
struct M : N
{
void operator delete(void* ptr1)
{
cout << "M :: operator delete" << endl;
}
};
int main()
{
N* ptr2 = new M;
delete ptr2;
}
-
View Hint View Answer Discuss in Forum
NA
Correct Option: C
In this program, We are passing the value to the M, So we are printing M::operator delete.
- What is the output of this program?
#include <iostream>
using namespace std;
struct OperatorA
{
virtual ~OperatorA()
{
cout << "~OperatorA()" << endl;
}
void operator delete[](void* p, size_t)
{
cout << "Operator A :: deleteed" << endl;
delete [] p;
}
};
struct OperatorB : OperatorA
{
void operator delete[](void* p, size_t)
{
cout << "Operator B :: operator deleteed" << endl;
delete [] p;
}
};
int main()
{
OperatorA* ptr = new OperatorB[2];
delete[] ptr;
};
-
View Hint View Answer Discuss in Forum
NA
Correct Option: A
In this program, the behavior of the statement delete[] ptr is undefined.
- What is the output of this program?
#include <iostream>
#include <new>
#include <cstdlib>
using namespace std;
const int bsize = 128;
int *ptr1;
bool allocate = true;
void get_memory()
{
cerr << "free store exhausted" << endl;
delete [] ptr1;
allocate = false;
}
void eat_memory(int size)
{
int *ptr2 = new int[size];
if (allocate)
eat_memory(size);
else
cerr << "free store addr = " << ptr2 << endl;
}
int main()
{
set_new_handler(get_memory);
ptr1 = new int[bsize];
cerr << "free store addr = " << ptr1 << endl;
eat_memory(bsize);
return 0;
}
-
View Hint View Answer Discuss in Forum
NA
Correct Option: B
In this program, The memory will go beyond the limit, So there will be exhaustion in memory.