Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/articles/c-tutorials/)
-   -   C Memory Allocation (http://www.go4expert.com/articles/c-memory-allocation-t29166/)

Trinity 6Oct2012 10:14

C Memory Allocation
 
When an ELF executable is executed, a process is created and its process image is create in the RAM. However, it is here in the process image in RAM, all the variables are assigned memory. Sometimes memory is allocated statically i.e. defined how much memory at the compile time, and at times it has to be allocated dynamically. Where, it is specified at run time the amount of memory needed.

Static Memory Allocation



First of all, please note, static memory allocation is not related to the ‘static’ variables in C programing.
Look at the following statement of a program:
Code:

int var = 30;
It is an initialized variable which is of datatype ‘int’ and has been allocated memory of the size of ‘int’ (lets say 4 bytes, which is a standard in Linux). Such kind of memory allocations are called static memory allocations. Note, at compile time we know here that ‘sizeof(int)’ amount of memory will be allocated. Here are some more examples of static memory allocation
Code:

char c;
float fvar;
int array[12];

This also explains why arrays take only constants as their sizes.

Worth mentioning, all such static memory allocations take place in the stack of the process image with certain exceptions like uninitialised global variables, const string pointers etc.

Dynamic Memory Allocations



In several cases, we might not know how much memory do we need at the compile-time. Its can only be specified at the run-time based on the value of a certain variable. For example, in the case of linked lists, where a node can be added/deleted at runtime, or matrices of varying rows/columns. For such scenarios, we have dynamic memory allocations. C provides following methods to allocate memory. Dynamic memory allocation always allocates memory in the heap of the process image.
Code:

      void *malloc(size_t size);
      void *calloc(size_t nmemb, size_t size);
      void *realloc(void *ptr, size_t size);

1. ‘malloc()’ is used for allocating a specific amount (in bytes) of memory. It returns a pointer to the memory allocated. However, the returned pointer is a void pointer which needs to be type-casted for regular use. It does not initialise the allocated memory. It returns a NULL pointer in case the allocations fails due to any reason. So, one can check for success/failure of this method by checking if the returned pointer is NULL or not. For more such details regarding malloc method, please refer its man page.

An example usage
Code:

int *ptr = NULL;
int amt = 30;
ptr = (int*) malloc ( amt * sizeof(int));

2. ‘calloc()’ is used for allocating a specific amount of a particle datatype of a memory. Hence, it takes two arguments as one can see in the syntax provided above. ‘calloc()’ also returns the pointer to the allocated chunk of memory, and it also needs the type casting. However, it attempts to initialise all the bits of the allocated memory to zero. It returns a NULL pointer in case the allocations fails due to any reason. For more details on this method, please refer to its man page.
An example usage
Code:

int *ptr = NULL;
ptr = (int*) malloc ( amt,  sizeof(int));

3. Another method for dynamic memory allocation is ‘realloc()’. The above two methods are there for fresh memory allocations. However, what if one just wants to expand/shrink an already allocated chunk of memory? For such cases we have ‘realloc()’. Depending upon the memory layout, it either just allocates the extra memory demanded or re-allocated the whole requested memory. It behaves similar to ‘malloc()’ as far as memory allocations are concerned.
An example usage
Code:

int *newPtr = NULL;
newPtr = (int*) realloc (ptr, amt + extra);

Note, ‘realloc()’ can also do fresh allocation of memory if the input pointer is a NULL.

Freeing up



Power comes with responsibility. Since C gives you the power to use and allocated memory as per our needs, hence it is the onus of the programmer to take care of allocated and free memory. Hence, freeing up of allocated memory is very essential in C programming and avoids many vulnerabilities.

All the statically allocated memory is free-ed automatically as its scope ends. However, the dynamically allocated memory have to be free-ed by the programmer. Here is the method which is used to free memory allocated on heap.
Code:

void free(void *ptr);

A complete example implementation



Here in this program, it highlights the usage and implementation details of the entire article.
Code:

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

int main()
{
    int size = 15; //static memory allocation
    int i; //static memory allocation
    int *mptr = NULL;
    int *cptr = NULL;

    //Using malloc
    mptr = (int*) malloc (size *sizeof(int)); //dynamic memory allocation
    if (mptr == NULL)
    {
        printf("Error in  memory allocation\n");
    }
    else
    {
        printf("Use new chunk of memory\n");
        for (i = 0; i < size; i++)
        {
            mptr[i] = i;
        }
    }

    //Using calloc
    cptr = (int*) calloc (size, sizeof(int)); //dynamic memory allocation
    if (cptr == NULL)
    {
        printf("Error in  memory allocation\n");
    }
    else
    {
        printf("Use new chunk of memory\n");
        for (i = 0; i < size; i++)
        {
            cptr[i] = i;
        }
    }

    //Using realloc
    size += size; //Increase size
    mptr = (int*) realloc (mptr, size * sizeof(int)); //extend the dynamic memory allocation
    if (mptr == NULL)
    {
        printf("Error in  memory allocation\n");
    }
    else
    {
        printf("Use new chunk of memory\n");
        for (i = 0; i < size; i++)
        {
            mptr[i] = i;
        }
    }

    //Free-ing up memory
    if (cptr)
        free(cptr);
    cptr = NULL;
    if (mptr)
        free(mptr);
    mptr = NULL;
    // No need to free size and i
   
    return 0;
}


paulkkarns 8Oct2012 11:53

Re: C Memory Allocation
 
Hi,

I am newbie here, nice sharing here its really interesting

sheikh 10Oct2012 18:51

Re: C Memory Allocation
 
PLease check this coe and solve my probem.this program given the area correct but when i try to sort the are i give an error please help me i know my syntax and logic is not well because i am new in programming

Code:

#include"stdafx.h"
#include<stdlib.h>
#include <iostream>
#include <conio.h>
using namespace std;
struct rectinfo
{
        int height,width,area,perimeter;
};

void genData (rectinfo*);
void calAreaPer (rectinfo*);
void display (rectinfo*);
void sort(rectinfo *r[],int);
int main()
{
        int n;
cout<<"ENter num please"<<endl;
cin>>n;
       
        rectinfo *shape=new rectinfo[n];
        for(int x=0;x<n;x++)
        {

        genData(&shape[x]);
calAreaPer(&shape[x]);
display(&shape[x]);
}sort(&shape,n);
        delete [] shape;
        return 0;
}


void genData (rectinfo* R)
{

R->height=rand()%21;
R->width=rand()%21;
       
}
void calAreaPer (rectinfo* A)
{
       
        A->area= (A->height*A->width);
        A->perimeter=2*(A->height + A->width);
       
}
void sort(rectinfo *r[],int size)
{
for(int y=0; y <size-1; y++)
{
for ( int k =1; k <size; k++ )
if(r[y]>r[k])
{
rectinfo *temp=r[y];
r[y] = r[k];
r[k] = temp;
}
}
//for(int yy=0;yy<size;yy++)
        //cout<<"area"<<r[yy]<<endl;
}
void display (rectinfo* B)
{
       
        cout<<"Randomnly generated value of height is "<<B->height<<endl;
        cout<<"Randomnly generated value of width is "<<B->width<<endl;
        cout<<"Area of rectangle is :"<<B->area<<endl;
        cout<<"Perimeter of rectangle is :"<<B->perimeter<<endl;

       
}


chinujhon 3Nov2012 13:45

Re: C Memory Allocation
 
hello... Memory is allocated in the form of block and metadata include the length of the block.When malloc() is called, the size of the allocated memory is kept somewhere. When free is called, it will use that stored size.
That is why we should only ever call free on a pointer that was returned by malloc().


All times are GMT +5.5. The time now is 17:56.