2

I have a few questions about understanding realloc behavior.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int *str;

    /* Initial memory allocation */
    str = malloc(5 * sizeof(int));
    *str = 1;
    *(str + 1) = 2;
    *(str + 2) = 3;
    *(str + 3) = 4;
    *(str + 4) = 5;

    /* Reallocating memory */
    int i, j;

    for (i = 5; i > 0; i--) {
        str = realloc(str, i * sizeof(int));

        for (j = 0; j < i; j++) {
            printf("%d", *(str + j));
        }  

        printf("\n");
    }

    free(str);

    return(0);
}
  1. In this code example, can I be sure that a smaller realloc will drop the highest number?

  2. Is the realloc is only freeing the last memory and keeping the same address in str? Or may the address change even though it's getting smaller and for sure have space in the current place?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
t.elazari
  • 300
  • 2
  • 11
  • 1
    `realloc()` is always allowed to move to a new address space. For instance, it might use different areas of memory for different size blocks. – Barmar Aug 12 '16 at 22:37
  • C99 and C11 are quite clear about `realloc()`: _The `realloc` function deallocates the old object pointed to by `ptr` and returns a pointer to a new object that has the size specified by `size`._ Sometimes, in some implementations, the new object has the same address as the old object, but the old object has technically been released. You can't access any of the previously allocated memory legitimately — doing so leads to undefined behaviour. You have no way, therefore, to test what happens. Most implementations won't move the data when shrinking memory — but there's no guarantee at all. – Jonathan Leffler Aug 12 '16 at 22:49

1 Answers1

4
  1. Yes. If you have a memory block p of size N and you do realloc(p, M), then (assuming realloc succeeds), the result will contain the first min(N, M) bytes from p.

  2. The address can change, even if the new size is smaller than the old one. realloc simply makes no guarantees about this case (it can even fail).

melpomene
  • 84,125
  • 8
  • 85
  • 148