| C Storage Class & Memory 1 | Main | Microsoft & C/Win32 | C++/OOP | Site Index | Download |


 

 

 

 

MODULE Z

THE C STORAGE CLASSES, SCOPE

AND MEMORY ALLOCATION 2

 

 

 

My Training Period: zz  hours

 

Note: gcc compilation examples are given at the end of this Module.

 

The abilities that supposed to be acquired:

 

 

 

 

 

 

 

 

 

 

 

 

Z.6  PROGRAM EXAMPLES

  • The following program example allocates memory using malloc().  In this program we cast the void * to int type.  There is no data stored in the memory requested; just an empty memory request and we do not de-allocate the memory as well.

/* playing with malloc(), memory on the heap */

#include <stdio.h>

#include <stdlib.h>

 

void main()

{

int x;

int *y;

/* do 100000 times iteration, 100000 blocks */

for(x=0; x<100000; x++)

{

/* For every iteration/block, allocate 16K,

system will truncate to the nearest value */

y = (int *)malloc(16384);

/* if no more memory */

if(y == NULL)

{

    puts("No more memory lol!");

    /* exit peacefully */

    exit(0);

}

/* allocate the memory block, print the block and the address */

printf("Allocating-->block: %i address: %p\n", x, y);

}

/* here, we do not free up the allocation */

}

 

Output:

 

Memory allocation function malloc()

 

/* playing with free(), memory on the heap */

#include <stdio.h>

#include <stdlib.h>

 

void main()

{

int x;

int *y;

int *buffer = NULL;

/* do 100 times iteration, 100 blocks */

for(x=0; x<100; x++)

{

    /* for every iteration/block, allocate 16K,

    system will truncate to the nearest value */

    y = (int *)malloc(16384);

    /* if there is a problem */

    if(y == NULL)

    {

        puts("No more memory for allocation lol!");

        /* exit peacefully */

        exit(0);

    }

    /* allocate the memory block, print the block and the address */

    printf("Allocating-->block: %i address: %p\n", x, y);

    printf("---->Freeing the memory block: %i address: %p\n", x, y);

    free((void *)buffer);

}

}

 

Output:

 

Memory allocation function malloc() free()

/* malloc() and struct */

#include <stdio.h>

#include <stdlib.h>

 

struct record{

char name[15];

int age;

int id_num;

};

 

int main()

{

    struct record *ptr;

    printf("\n--malloc() & struct--\n");

    ptr = (struct record *)malloc((sizeof(struct record)));

   

    if(ptr)

    {

        printf("\nStudent Name: ");

        gets(ptr->name);

        printf("Student Age: ");

        scanf("%d", &ptr->age);

        printf("Student Id: ");

        scanf("%d", &ptr->id_num);

        printf("\nStudent Name: %s", ptr->name);

        printf("\nStudent Age: %d", ptr->age);

        printf("\nStudent Id Number: %d\n", ptr->id_num);

        free(ptr);

}

else

    printf("\nMemory allocation fails!!!\n");

return 0;

}

 

Output:

 

Memory allocation function malloc() and structure

/* playing with malloc() and calloc() */

#include <stdio.h>

#include <stdlib.h>

 

#define END 10

 

int main()

{

    int *ptr1, *ptr2, *ptr3;

    int i;

    

    /* get memory for an array using malloc() - 1 parameter */

    ptr1 = (int *) malloc(END*sizeof(int));

    /* if memory allocation fails... */

    if (ptr1 == NULL)

    {

        fprintf(stderr, "malloc() failed!\n");

        /* exit with an error message */

        exit(1);

    }

    

    /* initialize the array using array notation */

    for(i = 0; i < END; i++)

    {

        ptr1[i] = i+i;

    }

    /*********************************************************/

    /* getting memory for an array using calloc() - 2 parameters */

    ptr2 = (int *) calloc(END, sizeof(int));

    /* if memory allocation fails... */

    if(ptr2 == NULL)

    {

       fprintf(stderr, "calloc() failed!\n");

        /* exit with an error message */

        exit(1);

    }

    /* initialize the array using pointer arithmetic */

    ptr3 = ptr2;

    for(i = 0; i < END; i++)

    {

        *(ptr3++) = i+i;

    }

    

    /* print array contents */

    printf("---Using malloc()---\n");

    printf("Array pointed by ptr1:\n");

    for(i = 0; i < END; i++)

    {

        printf("%3d ", ptr1[i]);

    }

    printf("\n\n");

   

    printf("---Using calloc()---\n");

    printf("Array pointed by ptr2:\n");

    for(i = 0; i < END; i++)

    {

        printf("%3d ", ptr2[i]);

    }

    printf("\n\n");

    return 0;

}

 

Output:

 

 

Memory allocation function malloc() and calloc()

/* calloc() and malloc() example */

#include <stdlib.h>

#include <stdio.h>

#define n 10

 

/* a struct */

typedef struct book_type

{

    int id;

    char name[20];

    float price;

}book;

 

int main(void)

{

    int *aPtr = NULL, *bPtr = NULL, m = 0;

    char *str = NULL;

    book *bookPtr = NULL;

   

    /* create an int array of size 10 */

    aPtr = (int *)calloc(n, sizeof(int));

    /* do some verification */

    if(aPtr == NULL)

    {

        printf("calloc for integer fails lol!\n");

        exit (0);

    }

    else

        printf("memory allocation for int through calloc() is OK\n");

    

    /* create a char array of size 10 */

    str = (char *)calloc(n, sizeof(char));

    if(str == NULL)

    {

        printf("calloc for char fails lol!\n");

        exit (0);

    }

    else

        printf("memory allocation for char through calloc() is OK\n");

    

    /* create a structure of book */

    bookPtr = (book *)malloc(sizeof(book));

    if(bookPtr == NULL)

    {

        printf("malloc for struct fails lol!\n");

        exit (0);

    }

    else

        printf("memory allocation for struct through malloc() is OK\n");

   

    /* clean up the memory allocated */

    free(aPtr);

    free(str);

    free(bookPtr);

   

    /* other way */

    /* get the number of elements from the user and then allocate */

    printf("\nEnter the size of integer array (bytes): ");

    scanf("%d", &m);

    bPtr = (int *)calloc(m, sizeof(int));

    if(bPtr == NULL)

    {

        printf("calloc for int fails lol!\n");

        exit (0);

    }

    else

        printf("memory allocation for int through calloc() is OK\n");

    free(bPtr);

    return 0;

}

 

Output:

 

 

 

 

 

 

 

 

 

 

 

-------------------------------------------------------------------------------------------------------------

 

 

 

 

Memory allocation function malloc() and calloc()

/* playing with realloc(). Store user input in an array */

#include <stdio.h>

#include <stdlib.h>

 

#define INITIAL_SIZE 5;

 

int main()

{

    int *Arr, *temp;

    int limit, input, n = 0, r, i;

   

    /* initially, allocate some space for A */

    limit = INITIAL_SIZE;

    Arr = (int *) malloc (limit * sizeof(int));

    /* do some verification, if fail */

    if (Arr == NULL)

    {

        /* display the error message */

        fprintf(stderr, "malloc() failed!\n");

        /* exit with the error code */

        exit(1);

    }

   

    /* array loop */

    printf("Enter numbers, 1 per line. End with ctrl-D\n");

    while(1)

    {

        printf("Next number: "); 

        r = scanf("%d", &input);

        fflush(stdin);

   

    /* verify the input */

    if(r < 1)

    break;

    /* get more space for Arr using realloc() */

    if(n >= limit)

    {

        printf("More than 5 elements per loop, reallocating the storage... \n");

        limit = 2 * limit;

        temp = (int *)realloc(Arr, limit * sizeof(int));

        /* verify again...*/

        if(temp == NULL)

        {

            fprintf(stderr, "realloc() failed!\n");

            exit(1);

        }

        else

            printf("realloc is OK lol, proceed your input...\n");

        Arr = temp;

    }

   

    Arr[n] = input;

    n++;

    }

   

    /* trim Arr down to size */

    temp = (int *)realloc(Arr, n*sizeof(int));

    /* verify... */

    if(temp == NULL)

    {

        fprintf(stderr, "realloc() fails lol!\n");

        exit(1);

    }

   

    Arr = temp;

   

    printf("\nContents of the array Arr:\n");

    /* print the array */

    for(i = 0; i < n; i++)

    {

        printf("%2d ", Arr[i]);

    }

    printf("\n");

    return 0;

}

 

Output:

 

Memory allocation function malloc() and realloc()

/* calloc() and malloc() example */

#include <stdlib.h>

#include <stdio.h>

#define n 10

 

/* a struct */

typedef struct book_type

{

    int id;

    char name[20];

    float price;

    }book;

   

int main(void)

{

    int *aPtr = NULL, *bPtr = NULL, m = 0;

    char *str = NULL;

    book *bookPtr = NULL;

   

    /* create an int array of size 10 */

    aPtr = (int *)calloc(n, sizeof(int));

    /* do some verification */

    if(aPtr == NULL)

    {

        printf("calloc for integer fails lol!\n");

        exit (0);

    }

    else

        printf("memory allocation for int through calloc() is OK\n");

   

    /* create a char array of size 10 */

    str = (char *)calloc(n, sizeof(char));

    if(str == NULL)

    {

        printf("calloc for char fails lol!\n");

        exit (0);

    }

    else

        printf("memory allocation for char through calloc() is OK\n");

    

    /* create a structure of book */

    bookPtr = (book *)malloc(sizeof(book));

    if(bookPtr == NULL)

    {

        printf("malloc for struct fails lol!\n");

        exit (0);

    }

    else

        printf("memory allocation for struct through malloc() is OK\n");

   

    /* clean up the memory allocated */

    free(aPtr);

    free(str);

    free(bookPtr);

   

    /* other way */

    /* get the number of elements from the user and then allocate */

    printf("\nEnter the size of integer array (bytes): ");

    scanf("%d", &m);

    bPtr = (int *)calloc(m, sizeof(int));

    if(bPtr == NULL)

    {

        printf("calloc for int fails lol!\n");

        exit (0);

    }

    else

        printf("memory allocation for int through calloc() is OK\n");

    free(bPtr);

    return 0;

}

[bodo@bakawali ~]$ gcc memalloc.c -o memalloc

[bodo@bakawali ~]$ ./memalloc

 

memory allocation for int through calloc() is OK

memory allocation for char through calloc() is OK

memory allocation for struct through malloc() is OK

 

Enter the size of integer array (bytes): 37

memory allocation for int through calloc() is OK

 

 

/**************** malalloc.c ************************** */

/************run on FeDora 3 Machine******************** */

/* playing with malloc() and free(), memory on the heap */

#include <stdio.h>

#include <stdlib.h>

 

int main()

{

    int x;

    int *y;

    int *buffer = NULL;

    /* do 100 times iteration, 100 blocks */

    for(x=0; x<100; x++)

    {

        /* for every iteration/block, allocate 16K,

        system will truncate to the nearest value */

        y = (int *)malloc(16384);

        /* if there is a problem */

        if(y == NULL)

        {

            puts("No more memory for allocation lol!");

            /* exit peacefully */

            exit(0);

        }

        else

        {

                /* allocate the memory block, print the block and the address */

                printf("Allocating-->block: %i address: %p\n", x, y);

                free((void *)buffer);

                printf("---->Freeing the memory block: %i address: %p\n", x, y);

        }

    }

    return 0;

}

 

[bodo@bakawali ~]$ gcc malalloc.c -o malalloc

[bodo@bakawali ~]$ ./malalloc

 

Allocating-->block: 0 address: 0x804a008

---->Freeing the memory block: 0 address: 0x804a008

Allocating-->block: 1 address: 0x804e010

---->Freeing the memory block: 1 address: 0x804e010

Allocating-->block: 2 address: 0x8052018

---->Freeing the memory block: 2 address: 0x8052018

Allocating-->block: 3 address: 0x8056020

---->Freeing the memory block: 3 address: 0x8056020

Allocating-->block: 4 address: 0x805a028

---->Freeing the memory block: 4 address: 0x805a028

Allocating-->block: 5 address: 0x805e030

---->Freeing the memory block: 5 address: 0x805e030

 

-----------------------------------o0o -----------------------------------

 

 

 

 

 

 

 

 

 

 

 

Further reading and digging:

 

  1. Check the best selling C and C++ books at Amazon.com.

  2. C and buffer overflow tutorial: stack frame activity.

  3. C and Assembler, Compiler and Linker.

  4. C lab worksheet practice.

 

 

| C Storage Class & Memory 1 | Main | Microsoft & C/Win32 | C++/OOP | Site Index | Download |


 

C Storage Class & Memory:  Part 1 | Part 2 |