当我们像这样动态地声明一些东西时
int *ptr = new int [100];然后更改指针地址(即指向其他地址)
int pointer[5] = {1,2,1,3,1,}; ptr = pointer ;那么包含100个整数的内存会发生什么?
无论如何重新控制那段记忆? 如果没有,是否会导致内存泄漏?
When we declare something dynamically like this
int *ptr = new int [100];and then change the pointer address (i.e point it to something else)
int pointer[5] = {1,2,1,3,1,}; ptr = pointer ;now what happens to that memory which contained 100 integers?
is there anyway to regain control of that memory ? and if not, does it lead to a memory leak?
最满意答案
那么包含100个整数的内存会发生什么?
它被“泄露”,因为你失去了你唯一的手柄。
无论如何重新控制那段记忆?
不,除非你在重新分配ptr之前注意创建另一个句柄。
int* ptr = new int[100]; int* ptr2 = ptr; ... ptr = pointer; delete [] ptr2;在实际代码中,您不会依赖原始指针来分配内存,而是使用最适合您问题的RAII类型(例如std::vector , std::unique_ptr等)
now what happens to that memory which contained 100 integers?
It is "leaked" because you lost the only handle you had to it.
is there anyway to regain control of that memory ?
No, unless you take care to create another handle before re-assigning ptr.
int* ptr = new int[100]; int* ptr2 = ptr; ... ptr = pointer; delete [] ptr2;In real code you would not rely on raw pointers to allocated memory, but rather use whichever RAII type works best for your problem (e.g. std::vector, std::unique_ptr etc.)
更多推荐
发布评论