Releasing Dynamically Allocated Memory - C Memory

C examples for Memory:free

Introduction

To release the memory for a block of dynamically allocated memory, use this statement:

free(pNumber);
pNumber = NULL;

The following code shows how to use pointers and dynamic memory allocation:

Demo Code

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

int main(void){
unsigned long long *pPrimes = NULL;  // Pointer to primes storage area
unsigned long long trial = 0;        // Integer to be tested
bool found = false;                  // Indicates when we find a prime
int total = 0;                       // Number of primes required
int count = 0;                       // Number of primes found

total = 5;/*from w  ww.  j  a v  a  2  s  .c  o  m*/

pPrimes = (unsigned long long*)malloc(total*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
trial = 5ULL;                        // Set to the last prime we have

while(count < total){
trial += 2ULL;                     // Next value for checking

// 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)                          // We got one - if found is true
*(pPrimes + count++) = trial;    // Store it and increment count
}
for(int i = 0 ; i < total ; ++i)  {
printf ("%12llu", *(pPrimes + i));
if(!((i+1) % 5))
printf("\n");                   // Newline after every 5
}
printf("\n");                       // Newline for any stragglers

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

Result 