user16310948
user16310948

Reputation:

How does realloc behave in C++ regarding extra Space?

Let's suppose I have allocated a block of size 40 like this:

int *x=malloc(40);

Now when I call realloc like this:

realloc(x,100);

what will happen to the other 60? Here are my suggestions.

A) Will be set to 0

B) Will Contain garbage from what malloc returned with a new allocation of 100

C) The first 40 are copied normally and the other 60 are copied too from the memory block after x. (goes out of bound).

Upvotes: 0

Views: 299

Answers (2)

Useless
Useless

Reputation: 67802

Here are my suggestions

Why are you speculating about something you can just look up?

For example, the POSIX documentation is here and says the last sixty bytes will be indeterminate.

You can look up the documentation for any platform if you want to know how that platform will behave (and don't care about portability), or you can just assume the values are undetermined.

A) Will be set to 0

Maybe on some platforms, and maybe sometimes on others, but it's not guaranteed.

B) Will Contain garbage from what malloc returned with a new allocation of 100

indeterminate values aren't necessarily garbage - they might all be zero. Or the new memory might be filled with 0xdeadbeef or some other magic value. You just shouldn't depend on any particular value - in fact, you shouldn't read this memory at all until you've written some known values into it.

Actually, I'm not even sure what the second half of that sentence means. The first forty bytes will be whatever you wrote into the original allocation, of course.

C) The first 40 are copied normally and the other 60 are copied too from the memory block after x. (goes out of bound)

That would make realloc illegal to use for its stated purpose, so obviously it can't be true.

The first forty bytes are copied from the old allocation, and you shouldn't depend on the next sixty bytes having any specific value until you put one there yourself.

Upvotes: 0

mediocrevegetable1
mediocrevegetable1

Reputation: 4217

realloc is a C function, so we can check its man page for a more detailed explanation of what realloc does. An excerpt (emphasis mine):

The realloc() function changes the size of the memory block pointed to by ptr to size bytes. The contents will be unchanged in the range from the start of the region up to the minimum of the old and new sizes. If the new size is larger than the old size, the added memory will not be initialized.

So B seems to be your answer.

(Note however that realloc may not necessarily be internally calling malloc in each call. Sometimes, you may notice that the pointer address has not changed before and after realloc. If there's still space after the previously malloc'd memory, realloc can just reserve that extra memory too instead of reallocating and copying everything).

Upvotes: 1

Related Questions