0

Suppose I have a character array allocated with new.Now, if I want to modify the size of the array then which of the following two is the best method ? 1. using realloc function OR 2.Allocate a new array, copy the data from old array to the new array and then delete the old array.

jairaj
  • 1,789
  • 5
  • 19
  • 32
  • 8
    Neither, use `std::string`. – chris Jan 04 '13 at 20:28
  • 2
    If you allocated an array with `new` (btw, you did mean `new[]` didn't you?) then don't use `realloc`. After all, you know what they say about randomly mixing different chemicals together, don't you? Think of memory management functions as chemicals. Just use `std::string`. – Nik Bougalis Jan 04 '13 at 20:31
  • 6
    Out of those 2 terrible options, 2 is the only possible correct answer, as 1 is undefined behavior. – Benjamin Lindley Jan 04 '13 at 20:32

4 Answers4

2

Allocate the block using malloc (not new) and then use realloc. realloc knows how much free space is available after the block for expansion.

s2 = realloc(s,<size>);
if (s2) {
   s = s2;
}
else {
   free up s and handle the error
}

Most code I have seen doesn't correctly handle failure of realloc.

DrC
  • 7,528
  • 1
  • 22
  • 37
1

You can't portably apply realloc to a buffer allocated with new. Hence only the second option of yours is viable.

Consider switching to std::vector and std::string.

ssegvic
  • 3,123
  • 1
  • 20
  • 21
  • Thanks, I know both are terrible options,but all I want to know is pure theoretical. – jairaj Jan 04 '13 at 20:38
  • The second option is not terrible at all. It's just that we usually achieve our goals with much less sweat by relying on the library code. If you are developing your own collection library then doing as you propose in option #2 may be a perfectly good design decision. – ssegvic Jan 04 '13 at 21:11
1

I think you are thinking about the whole matter from the C perspective.

if you are dealing with an array use a vector, it is dynamical and avoids the issues that you state in your question

e.g.

vector v(10); // allocates an array of 10 initialized to 0
v.push_back(42); // added another, so now array is 11 long
AndersK
  • 35,813
  • 6
  • 60
  • 86
1

The first option also implies copying if realloc finds that there is not enough free space after the block. (Even if you used malloc for allocating the array, which is the only correct option to use realloc at all.)

However, if you double the size of the array on each reallocation (or multiply its size by a constant > 1), the operation "increase array by one" uses constant time on average. Search for Constant Amortized Time.

Assume an array of initial size n. Reallocating to the new size 2n and copying costs 2n steps, but the next n "increase" operation are free.

By the way, this is how std::vector and many other array containers are implemented internally.

Community
  • 1
  • 1
krlmlr
  • 25,056
  • 14
  • 120
  • 217