Does malloc() always work to increase the size of an array?
If I use malloc()
to increase the s开发者_高级运维ize of an array, would that always work, or would I sometimes get a memory error?
It may be worth mentioning that malloc
will not increase the size of existing memory. It allocates new memory. realloc
can be used for "increasing" memory, but it is a tricky function at times (it can return a different pointer than the original, and if it fails to allocate new memory the original memory is left unchanged).
It'll "work" if you have enough memory. If you don't have enough memory, then it will not work.
Now, when I say "work", it depends what you mean by "work". malloc
does not increase the size of anything other than your program's memory usage.
Why aren't you using std::vector
?
realloc will return NULL
if it fails to allocate memory.
Malloc won't resize an array. And realloc will only do it for a malloc'd one.
精彩评论