Thursday, July 14, 2011

realloc

Now suppose you've allocated a certain number of bytes for an array but later find that you want to add values to it. You could copy everything into a larger array, which is inefficient, or you can allocate more bytes using realloc, without losing your data.realloc takes two arguments. The first is the pointer referencing the memory. The second is the total number of bytes you want to reallocate. Passing zero as the second argument is the equivalent of calling free. Once again, realloc returns a void pointer if successful, else a NULL pointer is returned.
This example uses calloc to allocate enough memory for an int array of five elements. Then realloc is called to extend the array to hold seven elements.

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

int main() {
int *ptr;
      int i;
      ptr = calloc(5, sizeof(int));
      if(ptr != NULL) {
            *ptr = 1;
            *(ptr+1) = 2;
            ptr[2] = 4;
            ptr[3] = 8;
            ptr[4] = 16;
            /* ptr[5] = 32; wouldn't assign anything */
            ptr = realloc(ptr, 7*sizeof(int));
            if(ptr != NULL) {
                  printf("Now allocating more memory... \n");
                  ptr[5] = 32; /* now it's legal! */
                  ptr[6] = 64;

                  for(i=0 ; i<7 ; i++) {
                        printf("ptr[%d] holds %d\n", i, ptr[i]);
                  }
                  realloc(ptr,0); //same as free(ptr); - just fancier!
                  return 0;
            }
            else {
                  printf("Not enough memory - realloc failed.\n");
                  return 1;
            }
      }
      else {
            printf("Not enough memory - calloc failed.\n");
            return 1;
      }
      return 0;
}

OutPut:
Now allocating more memory...
ptr[0] holds 1
ptr[1] holds 2
ptr[2] holds 4
ptr[3] holds 8
ptr[4] holds 16
ptr[5] holds 32
ptr[6] holds 64 

Notice the two different methods I used when initializing the array: ptr[2] = 4; is the equivalent to *(ptr+2) = 4; (just easier to read!).
Before using realloc, assigning a value to ptr[5] wouldn't cause a compile error. The program would still run, but ptr[5] wouldn't hold the value you assigned.

No comments:

Post a Comment