I am not sure what are the effects of using realloc() with new[]
It's undefined. Always.
arr = (T *)realloc(arr,sizeof(T)*newSize);
Note that the pattern p = realloc(p, size); is always, without exception, wrong.
The pattern must always be
Code:
T *tmp = realloc(p, size);
if(tmp == 0) {
// error out
return 1;
}
p = tmp;
That's because if realloc cannot find enough memory, it returns null and leaves the original block untouched. If you do p = realloc(p, size) in such a case, you'll overwrite the pointer to the old block with null. So not only did you not get a new block, you also lost the pointer to the old block (which then leaks).
Since in most programs and most parts of most programs, out-of-memory is not a recoverable situation, you can use something like this, though:
Code:
void *realloc_a(void *in, size_t newsize)
{
void *t = realloc(in, newsize);
if(!t) {
fprintf(stderr, "Failed to reallocate %d bytes of memory.\n", newsize);
abort();
}
return t;
}
Now you may do
Code:
p = realloc_a(p, size);
because realloc_a never returns null.
This is all only relevant to C, though. In C++, use a std::vector.