nikomaster nikomaster - 15 days ago 5
C++ Question

Dynamic memory resize char array

I'm trying resize a char array, i've followed:
Resizing a char[] at run time

then:

i've done something like this:

// this crashes in runtime:

const long SIZE_X = 1048576;

char* Buffsz = new char(sizeof(char));

for(int i = 0; i < (SIZE_X - 2); i++)
{
Buffsz[i] = 'a';
if(realloc(Buffsz, sizeof(char) * i) == NULL) // autoallocate memory
cout << "Failled to reallocate memory!" << endl;
}


but if I do:

// this works without problems.
const long SIZE_X = 1048576;

char* ABuffsz = new char[SIZE_X];

for(int i = 0; i < (SIZE_X - 2); i++)
{
ABuffsz[i] = 'a';
}

cout << "End success! len: " << strlen(ABuffsz) << endl;


For me this should be fine, but if it's wrong, how i can auto allocate memory?

P.S: I know about of use
std::vector
but i want use this if its possible.

Answer

realloc() is used to resize C-style arrays that were allocated with malloc(). realloc() cannot be used in C++ code, to resize C++ objects that were instantiated in dynamic scope with new.

There is no equivalent for realloc() in C++. In C++, the simplest way to resize an existing array is: a new array must be constructed in dynamic scope with new [], the values from the existing array std::copy-ed to the new array, and then the old array delete[]-ed.

That's a lot of work. This will involve a lot of unnecessary default-construction and copy-assignment (and if your classes do not have default constructors, you're stuck). Using placement-new and manual copy/move constructors it is possible to optimize some of this work. But it is a lot of work. And that's why you should use std::vector. It does all this for you, and it does this correctly.

There's nothing wrong with using new and delete yourself, as you would like to do. This is good learning experience, in order to gain some understanding how to properly manage dynamically-scoped objects. Fully understanding how low level dynamic scoping works is valuable knowledge to have. However, at some point all of this gets real old, and non-trivial tasks, involving dynamically-scoped objects, become tedious and error prone, and a major time-burner.

At that point, the only way to retain what's left of one's sanity is to start using C++ library containers, which take care of all the grunge work for you. In conclusion: use std::vector, and let it do all this work for you.