简体   繁体   English

增加免费存储上分配的内存的方法

[英]Way to increase memory allocated on free store

Is it possible to incrementally increase the amount of allocated memory on a free store that a pointer points to? 是否可以递增地增加指针指向的空闲存储区的已分配内存量? For example, I know that this is possible. 例如,我知道这是可能的。

char* p = new char; // allocates one char to free store
char* p = new char[10]; // allocates 10 chars to free store

but what if I wanted to do something like increase the amount of memory that a pointer points to. 但是如果我想做类似的事情来增加指针指向的内存量该怎么办。 Something like... 就像是...

char input;
char*p = 0;
while(cin >> input)  // store input chars into an array in the free store
    char* p = new char(input);

obviously this will just make p point to the new input allocated, but hopefully you understand that the objective is to add a new char allocation to the address that p points to, and store the latest input there. 显然,这只会使p指向分配的新输入,但是希望您理解目标是向p指向的地址添加一个新的char分配,并在其中存储最新的输入。 Is this possible? 这可能吗? Or am I just stuck with allocating a set number. 还是我只是坚持分配一个固定的数字。

The C solution is to use malloc instead of new -- this makes realloc available. C解决方案是使用malloc而不是new -这使realloc可用。 The C++ solution is to use std::vector and other nice containers that take care of these low-level problems and let you work at a much higher, much nicer level of abstraction!-) C ++解决方案是使用std :: vector和其他不错的容器来解决这些低级问题,并让您以更高,更好得多的抽象水平工作!

You can do this using the function realloc(), though that may only work for memory allocated with malloc() rather than "new" 您可以使用realloc()函数执行此操作,尽管这可能仅适用于使用malloc()分配的内存,而不是“ new”

having said that, you probably don't want to allocate more memory a byte at a time. 话虽如此,您可能不想一次分配一个字节更多的内存。 For efficiency's sake you should allocate in blocks substantially larger than a single byte and keep track of how much you've actually used. 为了提高效率,您应该在实质上大于单个字节的块中进行分配,并跟踪实际使用了多少字节。

You appear to be using C++. 您似乎正在使用C ++。 While you can use realloc, C++ makes it possible to avoid explict memory management, which is safer, easier, and likely more efficient than doing it yourself. 尽管可以使用realloc,但C ++可以避免显式的内存管理,这种内存管理比您自己进行更安全,更轻松并且可能更有效率。

In your example, you want to use std::vector as a container class for chars. 在您的示例中,您想将std :: vector用作chars的容器类。 std::vector will automatically grow as needed. std :: vector将根据需要自动增长。

In fact, in your case you could use a std::istreambuf_iterator and std:push_back to std::copy the input into a std::vector . 实际上,在您的情况下,您可以使用std :: istreambuf_iteratorstd:push_backstd::copy输入std::copystd::vector

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM