#include <iostream>
#include <cstdlib>
#include <new>
using namespace std;
void memwarning();
void* operator new(size_t, int);
void operator delete(void*);
int main()
{
char*p = new('$')char[100]; //Query 4b
cout<<endl<<"First allocation: p = " <<hex<<long(p)<<endl; // Query 1
for(int i=0;i<100;i++)
cout<<p[i];
cout<<endl;
delete p;// Query 2
p=new('*')char[64000u]; // Query 3
delete p;
return 0;
}
void memwarning()
{ cout<<endl<<"Free store has now gone empty";
exit(1);
}
void* operator new(size_t sz, int setvalue)
{
void *p;
p=malloc(sz);
if (p==NULL)
memwarning();
memset(p,setvalue, sz);
return (p); //Query 4a
}
void operator delete(void *pp)
{
free (pp);
}
Query 1) In this code the hex manipulator is printed before the address in p is converted to long....how come? since long(p) comes after hex in the code..
Query 2) please go through this sample program..
/* int *p1;
struct employee
{
char name[20];
int age;
float sal;
}; *p2;
p1=new int; // allocates 4 bytes
p2=new employee; // allocates 28 bytes
int *p3;
p3=new int[30]; // allocates memory for storing 30 integers
// some code
delete p1;
delete p2;
delete [ ] p3;
Note the last usage of the delete operator:
delete[ ]p3;
THE AUTHOR SAYS "It indicates that we are not deleting a thing but an array of things pointed to by pointer p3 would a simple
delete p3;
not work in this case? The compiler may not flag an error, but whether it would work successfully or not would vary from compiler to compiler. In some compilers the heap may get corrupted, in some others only the first object in the array would get deleted. In short, you would be better off if you use delete[ ] whenever you allocate memory using new [ ]. Otherwise be prepared for a disaster.*/
Ok, now why in the main program char array p is not deleted including the [ ] syntax????
Query 3) how come the compiler distinguished in the code p=new('*')char[64000u]; that it has to use global new and not custom new operator. What is the deciding factor?
Query 4) please observe the return type, we are returning a void pointer return (p); //Query 4a to char*p = new('$')char[100]; //Query 4b, here a void pointer cannot be assigned to a char pointer, but the inverse is possible i.e char pointer can be assigned to void pointer.