Extending Dynamically Allocated Memory - C Memory

C examples for Memory:realloc

Introduction

The realloc() function can reuse or extend memory allocated using malloc() or calloc() or realloc().

The realloc() function expects two argument values:

  • a pointer containing an address that was previously returned by a call to malloc(), calloc(), or realloc()
  • the size in bytes of the new memory that you want allocated.

realloc() preserves the contents of the original memory area.

If the new memory extent is greater than the old, then the added memory is not initialized.

Demo Code

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define CAP_INCR  10                   // New memory increment

int main(void){
  unsigned long long *pPrimes = NULL;  // Pointer to primes storage area
  bool found = false;                  // Indicates when we find a prime
  unsigned long long limit = 0LL;      // Upper limit for primes
  int count = 0;                       // Number of primes found

  limit = 50;//from w w  w . jav  a  2 s  .  c o  m

  size_t capacity = 10;
  pPrimes = (unsigned long long *)calloc(capacity, sizeof(unsigned long long));
  if(!pPrimes){
     printf("Not enough memory. It's the end I'm afraid.\n");
     return 1;
  }

  *pPrimes = 2ULL;                     // First prime
  *(pPrimes + 1) = 3ULL;               // Second prime
  *(pPrimes + 2) = 5ULL;               // Third prime
  count = 3;                           // Number of primes stored

  unsigned long long trial = *(pPrimes + 2) + 2ULL;
  unsigned long long *pTemp = NULL;    // Temporary pointer store
  while(trial <= limit){
    // Divide by the primes we have. If any divide exactly - it's not prime
    for(int i = 1 ; i < count ; ++i)
    {
      if(!(found = (trial % *(pPrimes + i))))
        break;                         // Exit if zero remainder
    }
    if(found){
      if(count == capacity){ 
        capacity += CAP_INCR;
        pTemp = (unsigned long long *)realloc(pPrimes, capacity*sizeof(unsigned long long));
        if(!pTemp){
          printf("Unfortunately memory reallocation failed.\n");
          free(pPrimes);
          pPrimes = NULL;
          return 2;
        }
        pPrimes = pTemp;
      }
      *(pPrimes + count++) = trial;   // Store the new prime & increment count
    }
    trial += 2ULL;
  }

  printf("%d primes found up to %llu:\n", count, limit);
  for(int i = 0 ; i < count ; ++i){
    printf("%12llu", *(pPrimes + i));
    if(!((i+1) % 5))
      printf("\n");                   // Newline after every 5
  }
  printf("\n");                   

  free(pPrimes);                  
  pPrimes = NULL;                 
  return 0;
}

Result


Related Tutorials