How to prove that the delete operator is working?

My CS teacher asked me to prove to her that the delete operator is working?

I wrote the following code:

#include<iostream>
using namespace std;
struct abc
{
int *prats;
int a;
};
int main()
{
abc ob;
ob.prats=new int;
cout<<"size before delete: ";
cout<<sizeof(abc)<<endl;
delete ob.prats;
cout<<"Size after delete: ";
cout<<sizeof(abc);
}

bUt the output is 4 in both the cases, Why??

And if this is not the way to prove that delete is working.. Then what is the way??
Do you believe that when you call delete you destroy your computer's RAM? No, your computer always has the same amount of memory - what you are really doing is telling the operating system "I'm done with this memory, you can give it to another program"

The easiest way to prove that it is working is to use valgrind.
closed account (48T7M4Gy)
cout << ob.prats; after delete should produce an error.
@kemort: how? It will print a memory address. It is always valid to print a memory address even if you can't access the memory at that address.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <iostream>

void* operator new( std::size_t sz )
{
    void* pv = std::malloc(sz) ;
    if( !pv ) throw std::bad_alloc() ;
    std::cout << "allocated memory at address " << pv << '\n' ;
    return pv ;
}

void operator delete( void* pv ) noexcept
{
    if(pv)
    {
        std::free(pv) ;
        std::cout << "deallocated memory at address " << pv << '\n' ;
    }
}

void operator delete( void* pv, std::size_t ) noexcept { ::operator delete(pv) ; }

void* operator new[] ( std::size_t sz ) { return ::operator new(sz) ; }
void operator delete[] ( void* pv ) noexcept { return ::operator delete(pv) ; }
void operator delete[] ( void* pv, std::size_t ) noexcept { return ::operator delete[](pv) ; }

int main()
{
    struct A
    {
        A() { std::cout << "A::constructor - object is at address" << this << '\n' ; }
        ~A() { std::cout << "A::destructor - object was at address" << this << '\n' ; }
    };

    constexpr std::size_t N = 3 ;
    A* a[N]{} ;

    for( auto& p : a ) p = new A ;
    std::cout << "-----------------\n" ;

    auto arr = new A[N] ;
    std::cout << "-----------------\n" ;

    for( auto& p : a ) delete p ;
    std::cout << "-----------------\n" ;

    delete[] arr ;
}

http://coliru.stacked-crooked.com/a/91748a6e16ad4447
http://rextester.com/PYJU62896
closed account (48T7M4Gy)
cout << *(ob.prats); = 0

Oops! :-)
Last edited on
@kemort: that's still not guaranteed to generate any kind of error, it will just invoke undefined behavior. Most likely nothing at all will happen, and it will just output garbage.
Last edited on
closed account (48T7M4Gy)
@LB
cout << *(ob.prats);

prints '0' which I agree is not an error.

But, a second delete ob.prats; produces an error
Last edited on
Topic archived. No new replies allowed.