c++ - 将一个数组的内容复制到另一个数组会导致内存泄漏吗

标签 c++ memory memory-leaks

这段代码是否会导致内存泄漏:

int main(){

   int * a = new int[10];
   int * b  = new int[10];
   for(int i = 0 ; i < 10; i++)
   {
       a[i] = 1;
       b[i] = 1;
   }

   for(int i = 0 ; i < 10; i++)
   {
       a[i] = b[i]; //each a[i] is allocated 4 bytes on heap
                    //when we copy b[i] into a[i] do we loose 
                    //the reference to a[i] (hence a leak), 
                    //and replace that reference
                    //with a reference to a new value?
   }

   delete[] a;
   delete[] b;


}

最佳答案

不,那里没有泄漏。您只是在复制数组中的值。将阵列想象成更衣室中的两排储物柜——您只需复制一个储物柜中的内容,然后将其放入另一排储物柜中;储物柜本身留在原处。

关于c++ - 将一个数组的内容复制到另一个数组会导致内存泄漏吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1579663/

相关文章:

c++ - 字符串类构造函数安全

c++ - 我必须在类的头文件中提及私有(private)方法吗?

c++ - C++字符串程序引起的运行时错误

ios - 在应用程序运行时检查内存使用情况

c++ - 在 C++ 中使用指针 vector 时会泄漏内存吗?

c++ - 使用 std::array 作为 boost::spirit::x3 的属性

r - 输入矩阵的每一行需要包含至少一个非零项

.net - Windows API根据未使用的变量名称导致不同的结果?

java - Java 中的内存泄漏。如何清除列表?

android - DDMS 和操作系统显示关于我的应用程序的不同内存信息