strange
March 29th, 2004, 02:36 PM
Hi,
I've found some strange behaviour of the new and delete operators.
The following code overwrites the new, new[], delete and delete[] operators, adding a message being printed every time they are called. Then I use each operator once and get some unexpected behaviour. The code is:
#include <iostream>
#include <vector>
using namespace std;
inline void* operator new (unsigned int size)
{
cout << "new: " << size << "\n";
return malloc(size);
}
inline void* operator new[] (unsigned int size)
{
cout << "new[]: " << size << "\n";
return malloc(size);
}
inline void operator delete (void * buf)
{
cout << "delete\n";
free(buf);
}
inline void operator delete[] (void * buf)
{
cout << "delete[]\n";
free(buf);
}
#pragma argsused
int main (char * argv, unsigned int argc)
{
vector<int> *var = new vector<int>;
vector<int> *arr = new vector<int>[1];
delete var;
delete[] arr;
return 0;
}
and the program output is:
new: 32
new[]: 36
delete
delete
delete
leaving two questions:
[list=1]
why are there two 'delete's and no 'delete[]'?
why is an array with size 1 four bytes larger than a plain variable? (with integer this is NOT the case)
[/list=1]
Thanks!
I've found some strange behaviour of the new and delete operators.
The following code overwrites the new, new[], delete and delete[] operators, adding a message being printed every time they are called. Then I use each operator once and get some unexpected behaviour. The code is:
#include <iostream>
#include <vector>
using namespace std;
inline void* operator new (unsigned int size)
{
cout << "new: " << size << "\n";
return malloc(size);
}
inline void* operator new[] (unsigned int size)
{
cout << "new[]: " << size << "\n";
return malloc(size);
}
inline void operator delete (void * buf)
{
cout << "delete\n";
free(buf);
}
inline void operator delete[] (void * buf)
{
cout << "delete[]\n";
free(buf);
}
#pragma argsused
int main (char * argv, unsigned int argc)
{
vector<int> *var = new vector<int>;
vector<int> *arr = new vector<int>[1];
delete var;
delete[] arr;
return 0;
}
and the program output is:
new: 32
new[]: 36
delete
delete
delete
leaving two questions:
[list=1]
why are there two 'delete's and no 'delete[]'?
why is an array with size 1 four bytes larger than a plain variable? (with integer this is NOT the case)
[/list=1]
Thanks!