#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
int* a = new int;
*a = 5;
int* b = new int;
*b = 6;
int* temp = a;
delete(a);
a = b;
b = temp;
cout << *temp << endl;
delete (temp); // error
return 0;
}
error : malloc: *** error for object 0x7ffdff400630: pointer being freed was not allocated. But if I do not delete(a)
, it works.
When you use
int* temp = a;
both a
and temp
point to the same memory that was allocated in the line
int* a = new int;
When you use
delete(a);
that memory was deallocated. At that time, both temp
and a
are dangling pointers.
By using
a = b;
b = temp;
you changed a
to point to a valid memory but now both b
and temp
are dangling pointers.
Use of temp
in
cout << *temp << endl;
delete (temp); // error
is not correct. Both of them are cause for undefined behavior. With undefined behavior, it is pointless to try to make sense of what happens -- anything can happen.
But if I do not
delete(a)
, it works.
That makes sense. Without that call, all the pointers continue to be valid till the end of the function.
You should add code to delete both the pointers before the end of the function though. But then you have to keep track of which pointers are valid to be used in the calls to delete
.
You can print their values to figure that out.
std::cout << "a: " << (void*)a << std::endl;
std::cout << "b: " << (void*)b << std::endl;
std::cout << "temp: " << (void*)temp << std::endl;
In
int* temp = a;
You make copy of the pointer, So a
and temp
points to same thing, Then in
delete a;
You delete a
so temp
becomes a dangling pointer, de-referencing it causes undefined behavior.
Ideally you should do
temp = null;
just after the delete
or for the better use shared pointer that ships with modern CPP.
#include <iostream>
#include <memory>
auto main() -> int
{
auto ptr = std::make_shared<int>(5);
std::cout << "ptr value is " << *ptr << std::endl;
auto ptr1 = ptr; // Reference counted copy
std::cout << "ptr value is " << *ptr1 << std::endl;
std::cout << "Total reference count :" << ptr1.use_count() << std::endl;
ptr.reset(); // Resetting ptr, thus reference count drops to 1
std::cout << "Total reference count :" << ptr1.use_count() << std::endl;;
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.