经由“新”存储器重新分配存储器。在C ++中 [英] Reallocating memory via "new" in C++

查看:169
本文介绍了经由“新”存储器重新分配存储器。在C ++中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于C ++内存管理的快速问题



如果我执行以下操作:

  pointer = new char [strlen(someinput_input)+1]; 

然后再次执行,可能会从 strlen返回不同的结果(someinput_input)



这会导致内存从上一个 new 语句?在每个 new 语句从操作系统接收另一块HEAP内存,或者它只是重新分配?



假设我做了一个最终的删除指针[]; 将通过 new c>

delete 的相应调用相匹配。



另外,您应该考虑使用 std :: string 或者甚至 std :: vector< char> (取决于具体情况),而不是尝试自己分配字符数组。那么你不需要担心。


Quick question regarding memory management in C++

If I do the following operation:

pointer = new char [strlen(someinput_input)+1];

And then perform it again, with perhaps a different result being returned from strlen(someinput_input).

Does this result in memory being left allocated from the previous "new" statement? As in, is each new statement receiving another block of HEAP memory from the OS, or is it simply reallocating?

Assuming I do a final delete pointer[]; will that deallocate any and all memory that I ever allocated via new to that pointer?

解决方案

Every call to new must be matched with a corresponding call to delete.

As an aside, you should probably consider using std::string or even std::vector<char> (depending on the exact situation), rather than trying to allocate char arrays yourself. Then you don't ever need to worry.

这篇关于经由“新”存储器重新分配存储器。在C ++中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆