c++memorymallocreallocmemmove

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).


Solution

  • 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.