Showing posts with label Memory Management. Show all posts
Showing posts with label Memory Management. Show all posts

Saturday, August 11, 2012

Creating a Dynamic Matrix in ANSI C

The memory of a dynamic matrix can be allocated at run time as opposite to the static matrices (who are allocated at compile-time).

The allocation algorithm is based on the function void* malloc(size_t size). The first thing that must be done is to allocate the space for the entire matrix. After that, each row from the matrix must be allocated separately.
/*
 * Description:
 *  Allocates dinamically memory for a rows x columns matrix
 * Parameters:
 *  matrix  - a pointer to the matrix which will be allocated
 *  rows    - the number of rows
 *  columns - the number of columns
 * Returns:
 *  matrix - a pointer to the allocated matrix
 */
int** Matrix_Alloc(int** matrix, int rows, int columns)
{
    int i;
    matrix=malloc(sizeof(int)*rows*columns);
    if(matrix!=NULL)
    {
        /*Allocating space for each row*/
        for(i=0; i<rows;i++)
        {
            matrix[i] = malloc(sizeof(int)*columns);
            if(matrix[i]==NULL)
            {
                return NULL;
            }
        }
    }
    return matrix;
}
The deallocation algorithm is based on the function void free(void* address) and is pretty much the opposite of the allocation algorithm, First the rows of the matrix will be deallocated and then the matrix itself.
/*
 * Description:
 *  Frees a dynamically allocated matrix
 * Parameters:
 *  matrix  - a pointer to an allocated matrix
 *  rows    - the number of rows
 *  columns - the number of columns
 * Returns:
 *  Nothing
 */
void Matrix_Free(int** matrix, int rows)
{
    int i;
    for(i = 0; i < rows; i++)
    {
        free(matrix[i]);
    }
    free(matrix);
}
Here's an example on how to use the functions:
#include<stdio.h>
#include<stdbool.h>
#include<stdlib.h>

int** Matrix_Alloc(int** matrix, int rows, int columns);
void Matrix_Free(int** matrix, int rows);

void Matrix_Print(int** matrix, int rows, int columns)
{
    int i,j;
    for(i=0; i<rows;i++)
    {
        for(j=0; j<columns; j++)
        {
            printf("%d ",matrix[i][j]);
        }
        putchar('\n');
    }
}

int main(void)
{
    int **matrix = NULL;
    int i, j;

    /*Allocating the matrix*/
    matrix = Matrix_Alloc(matrix, 3, 3);

    /*Assigning values to the matrix*/
    for (i = 0; i < 3; i++)
    {
        for (j = 0; j < 3; j++)
        {
            matrix[i][j] = (i+j);
        }
    }

    /*Printing the results*/
    Matrix_Print(matrix,3,3);

    /*Freeing the memory*/
    Matrix_Free(matrix,3);
    puts("Memory freed");

    return 0;
}
/*Output
0 1 2 
1 2 3 
2 3 4 
Memory freed
*/
In the example above we used a primitive data type. If we would had use a structure, each element of the matrix would had to be allocated/freed as well.

Tuesday, October 18, 2011

Checking when an Object is Destroyed in Java

As you may know, Java has no destructors like C++ or C#. Still, there is a method that allows you to check when an object is destroyed (or "collected") by the Garbage Collector (Java's mechanism to free up the memory that is no longer used by your program).

To check this, your class needs to contain a finalize method. The finalize method also needs to call the finalize method of its superclass (all Java classes inherit the Object class by default if there is no other class specified). Your code needs (or rather say it's recommended) to be included in the try block.
protected void finalize() throws Throwable 
{
        try
        {
            //TO DO CODE
        }
        finally
        {
            super.finalize();
        }
}
This method is useful if you want to check out the exact moment when a certain object is destroyed or if you want to keep track of how many object of a certain class exist in the program's memory.

If you want to signal when an object is destroyed:
protected void finalize() throws Throwable 
{
        try
        {
            System.out.println("Object destroyed of type" 
                             + this.getClass().toString());
        }
        finally
        {
            super.finalize();
        }
}
If your class has an toString method implemented the method could look like (you could see this way the specific object who was destroyed):
protected void finalize() throws Throwable 
{
        try
        {
            System.out.println("Object destroyed : " + this.toString());
        }
        finally
        {
            super.finalize();
        }
}
If your application is not console, you will probably need to replace the println method with a more "visual" method (which depends of you GUI framework, or the control in which you want to display the information).

If you want to keep track on how many object of a certain class exist in the program's memory:
public class MemoryTest 
{
      //Static counter variable
      private static int count = 0;
      //The object's id
      private int myId;
      //Constructor
      public MemoryTest() 
      {
        myId = count;
        count++;
        System.out.println("Object created" + myID);
      }
      //Finalize method implementation
      protected void finalize() throws Throwable 
      {
        try
        {
            System.out.println("Object destroyed " + myId);
        }
        finally
        {
            super.finalize();
        }
     }
}
According to the Java reference, an object is collected by the Garbage Collector when he is no longer referenced in the program. So, theoretically, he will be destroyed. Still, this rule does not always apply, because the Garbage Collector has a tendency to free up memory only when the program's memory is full.

Thursday, September 1, 2011

The Dynamic Multidimensional Arrays Library

The Dynamic Multidimensional Arrays Library provides functions for the allocation and deallocation of arrays, matrices, cubes and hypercubes.

In order to pass any kind of data type to the functions, we shall pass the array to the functions using a void pointer. Also, for each allocation function, the size of an array's element must be passed.

The prototypes for the functions are:
/*
 * Abstract:
 *  Allocates a 1D array
 * Parameters:
 *  vector - a pointer to the 1D array
 *  xsize - the size of the array
 *  elementSize - the size of one element
 * Returns:
 *  A pointer to the allocated array
 */
void* NAlloc1D(void* vector, size_t xsize, size_t elementSize);
/*
 * Abstract:
 *  Allocates a 2D array
 * Parameters:
 *  vector - a pointer to the 2D array
 *  xsize - the x size of the array (real of rows)
 *  ysize - the y size of the array (real of columns)
 *  elementSize - the size of one element
 * Returns:
 *  A pointer to the allocated array
 */
void** NAlloc2D(void **vector, size_t xsize, size_t ysize, size_t elementSize);
/*
 * Abstract:
 *  Allocates a 3D array
 * Parameters:
 *  vector - a pointer to the 3D array
 *  xsize - the x size of the array (real of rows)
 *  ysize - the y size of the array (real of columns)
 *  zsize - the z size of the array (real of tables)
 *  elementSize - the size of an array element
 * Returns:
 *  A pointer to the allocated array
 */
void*** NAlloc3D(void ***vector, size_t xsize, size_t ysize, size_t zsize,
        size_t elementSize);
/*
 * Abstract:
 *  Allocates a 4D array
 * Parameters:
 *  vector - a pointer to the 4D array
 *  xsize - the x size of the array (real of rows)
 *  ysize - the y size of the array (real of columns)
 *  zsize - the z size of the array (real of tables)
 *  tsize - the t size of the array
 *  elementSize - the size of an array element
 * Returns:
 *  NULL
 */
void**** NAlloc4D(void ****vector, size_t xsize, size_t ysize, size_t zsize,
        size_t tsize, size_t elementSize);

/*Deallocation functions*/
/*
 * Abstract:
 *  Deallocates a 1D array
 * Parameters:
 *  vector - a pointer to the 1D array
 * Return:
 *  NULL
 */
void* NFree1D(void *vector);
/*
 * Abstract:
 *  Deallocates a 2D array
 * Parameters:
 *  vector - a pointer to the 2D array
 *  xsize - the x size of the array (real of rows)
 * Returns:
 *  NULL
 */
void** NFree2D(void **vector, size_t xSize);
/*
 * Abstract:
 *  Deallocates a 3D array
 * Parameters:
 *  vector - a pointer to the 3D array
 *  xsize - the x size of the array (real of rows)
 *  ysize - the y size of the array (real of columns)
 * Returns:
 *  NULL
 */
void*** NFree3D(void ***vector, size_t xsize, size_t ysize);
/*
 * Abstract:
 *  Deallocates a 4D array
 * Parameters:
 *  vector - a pointer to the 3D array
 *  xsize - the x size of the array (real of rows)
 *  ysize - the y size of the array (real of columns)
 *  zsize - the z size of the array (real of tables
 * Returns:
 *  NULL
 */
void**** NFree4D(void ****vector, size_t xsize, size_t ysize, size_t zsize);

5.Example
#include<stdio.h>
#include"dmda.h"

int main()
{
    int** array = NULL;
    int i,j;
    /*Creating a 10x10 2-dimensional numeric array*/
    array = (int**)NAlloc2D((int**)array,10,10,sizeof(int));
    /*Initializing the array with values*/
    for(i=0; i<10; i++)
    {
        for(j=0; j<10; j++)
        {
            array[i][j] = i-j;
        }
    }
    /*Displaying the 2-dimensional array*/
    for(i=0; i< 10; i++)
    {
        for(j=0; j<10; j++)
        {
            printf("%+d ",array[i][j]);
        }
        putchar('\n');
    }
    /*Freeing the 2-dimensional array*/
    array = (int**)NFree2D((int**)array,10);
    puts("Memory freed");
    return 0;
}
/*Output
+0 -1 -2 -3 -4 -5 -6 -7 -8 -9
+1 +0 -1 -2 -3 -4 -5 -6 -7 -8
+2 +1 +0 -1 -2 -3 -4 -5 -6 -7
+3 +2 +1 +0 -1 -2 -3 -4 -5 -6
+4 +3 +2 +1 +0 -1 -2 -3 -4 -5
+5 +4 +3 +2 +1 +0 -1 -2 -3 -4
+6 +5 +4 +3 +2 +1 +0 -1 -2 -3
+7 +6 +5 +4 +3 +2 +1 +0 -1 -2
+8 +7 +6 +5 +4 +3 +2 +1 +0 -1
+9 +8 +7 +6 +5 +4 +3 +2 +1 +0
Memory freed
 */
Related Posts Plugin for WordPress, Blogger...