Wednesday, May 21, 2014

Messing Around with C and Pointer Stuff

/*
An exercise in getting to grips with pointers and dynamic memory allocation. 

This program checks to see the largest chunk of memory that can be allocated on a RHEL system with 4GB memory.

Used some made up algorithm which is probably not very efficient but the purpose of this exercise was not to write efficient algorithms but just for my edification.
*/

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

long lb = 0;
long ub = 4140949504;
const int O_SUCCESS = 0;
const int O_FAIL = 1;

void fx(long *, long *);
void range_calc(long *, long *, long *, int);

int main(void)
{
   char text[500];
   long sz, arr=10;
   fx(&lb, &ub);
   return 0;
}

void fx(long *p_lb, long *p_ub)
{
   long *array;
   long ctr = 0;
   int status = O_SUCCESS;
   long crnt_lb, crnt_ub, prev_lb, prev_ub;
   prev_lb = *p_lb; prev_ub = *p_ub;
   long mem_sz_to_test = prev_ub;

   while (1)
   {
      array = (long *)malloc(mem_sz_to_test * sizeof(long));

      if (array == 0)
      {
         printf("ERROR: While trying to allocate %lu bytes\n", mem_sz_to_test);
         // Split the range in half, test the lower limit
         crnt_ub = mem_sz_to_test;
         range_calc(&crnt_ub, &prev_lb, &crnt_lb, O_FAIL);
         mem_sz_to_test = crnt_lb;
         printf("1.\tlb = %lu, ub = %lu\n", crnt_lb, crnt_ub);
         printf("mem_sz_to_test = %lu\n", mem_sz_to_test);
      }
      else
      {
         printf("Allocated = %lu bytes\n", mem_sz_to_test * sizeof(long));
         free(array);
         prev_lb = crnt_lb;
         // Split the range in half, test the lower limit
         range_calc(&crnt_ub, &prev_lb, &crnt_lb, O_SUCCESS);
         printf("2.\tlb = %lu, ub = %lu\n", crnt_lb, crnt_ub);
         mem_sz_to_test = crnt_lb;
      }
      printf("ctr = %d\n\n", ctr++);
      if (ctr == 2500 || crnt_lb == crnt_ub) break;
   }
}


// Do the range split in half routine here
void range_calc(long *p_crnt_ub, long *p_prev_lb, long *p_crnt_lb, int STATUS)
{

   if (O_FAIL)
   {
      *p_crnt_lb = (*p_crnt_ub - *p_prev_lb)/2 + *p_prev_lb;
      if (*p_crnt_lb % 2 != 0)
         *p_crnt_lb = *p_crnt_lb + 1;
   }

   if (O_SUCCESS)
   {
      *p_crnt_lb = (*p_crnt_ub - *p_crnt_lb)/2 + *p_crnt_lb;
      if (*p_crnt_lb % 2 != 0)
         *p_crnt_lb = *p_crnt_lb + 1;
   }
}

No comments:

Post a Comment