What will happen if someone tries to access freed memory?

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  
#include <iostream>

using namespace std;

int main()
{
    int* pt=new int;

    *pt= 1000;

    cout<<"The value of pt is "<<*pt<<endl;
    cout<<"The  address of pt is "<<pt<<endl;

    delete pt;

    cout<<*pt;

    return 0;
}
is it a memory leak ??
What will happen if someone tries to access freed memory?

It's called "undefined behavior".

If you're running a debug build, you will probably get a trap (implementation specific). If you're running a release build, you read or write whatever is in that memory location, which might have been assigned to something else.

is it a memory leak ??

No. You allocate the pointer at line 8 and release it at line 15. No memory leak.


Last edited on
closed account (E0p9LyTq)
What will happen if someone tries to access freed memory?

What exactly will happen depends on the compiler.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

int main ()
{
   short* short_ptr = new short{12};

   std::cout << short_ptr << ",\t" << *short_ptr << "\n\n";

   delete short_ptr;

   long* long_ptr = new long{123456};   

   std::cout << short_ptr << ",\t" << *short_ptr << "\n";
   std::cout << long_ptr << ",\t" << *long_ptr << "\n\n";

   *short_ptr = 125; // uh-oh!

   std::cout << short_ptr << ",\t" << *short_ptr << "\n";
   std::cout << long_ptr << ",\t" << *long_ptr << "\n";
}

The example above compiles in both TDM GCC 4.9.2 and MS Visual C++ 2015 Community. Differences occur when running the resulting executable.

TDM GCC produces the following output:
0x182510,       12

0x182510,       -7616
0x182510,       123456

0x182510,       125
0x182510,       65661


MSVC++ produces the following output:
0x182510, 12


And then crashes with a "read access violation." Writing to a deleted pointer would also crash, *short_ptr = 125;, with a "write access violation" if the program had not already terminated.

One thing to note is that new assigns memory addresses differently between TDM GCC and MSVC++. MSVC++ may not assign the same memory location to a new pointer as a previously deleted pointer:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>

int main ()
{
   short* short_ptr = new short{12};

   std::cout << short_ptr << ",\t" << *short_ptr << "\n\n";

   delete short_ptr;

   long* long_ptr = new long{123456};   

   std::cout << long_ptr << ",\t" << *long_ptr << "\n";
}

006E2C28,       12

006E2BF8,       123456


If you are lucky trying to access a deleted pointer, read or write, will crash the program immediately. Corrupting memory while continuing to run, as TDM GCC does, is hard to debug.
Last edited on
Topic archived. No new replies allowed.