Wednesday

malloc(),calloc(),realloc()and free()


malloc()

             The malloc()  function dynamically allocates memory when required. This function allocates ‘size’ byte of memory and returns a pointer to the first byte or NULL if there is some kind of error.span>
Format is as follows.

void * malloc (size_t size);

Specifies in bytes the size of the area you want to reserve the argument. It returns the address as the return value of the dynamically allocated area. In addition, returns NULL if it fails to secure the area. The failure to ensure that the situation is usually that is out of memory.

The return type is of type void *, also receive the address of any type. The fact is used as follows.

double * p = (double *) malloc (sizeof (double));

The size of the area using the sizeof operator like this. The return value is of type void *, variable in the receiving side can be the pointer of any type in the host language C language called C + +, the pointer type to other type void * is, without casting, so can not be assigned, Use a cast. In C, a pointer type to void * type from another, so that the cast automatically, there is no need to explicitly cast originally.Of course, should not write because not explicitly given as well as portability to C + +, I wrote better.
In addition, the secured area is unknown at this point that's on it? That is the same as a normal state to declare a local variable. Thus, with reference values ??must not be left without initialization.
          
With this feature, you get a pointer to an allocated block of memory. Its structure is:

code:

pointer = (type) malloc (size in bytes);

An example:code:


int * p;
p = (int *) malloc (sizeof (int));
* p = 5;

First we declare a pointer, which is still pointing nowhere. Then the pointer, not the content but the pointer itself is equal to a pointer type int that contains the memory address space for an int. Sizeof () gets the space it occupies what you want, if you put int in, such as 2 bytes, because we have assigned two bytes. This feature also serves to get the size of pointers, variables, or whatever it takes.
Finally, now that the pointer is contained, we give a value.
For example:
               int *ptr = malloc(sizeof(int) * 10);      // allocates 10 ints!
                 If it is unable to find the requested amount of memory, malloc() function returns NULL. So you should really check the result for errors:
int *ptr = malloc(sizeof(int) * 5000);
if (ptr == NULL)
       {
       printf(" Out of memory!\n");
       exit(1);
       }
                 There are only two ways to get allocated memory back. They are exit from the program and calling free() to free function. If your program runs a while and keeps malloc()ing and never free()ing when it should, it is said to “leak” memory. Make sure to avoid memory leaks! free() that memory when you are done with it!

The following example illustrates the use of  malloc() function.

calloc() function

           

The calloc function is used to allocate storage to a variable while the program is running. This library function is invoked by writing calloc(num,size).This function takes two arguments that specify the number of elements to be reserved, and the size of each element in bytes and it allocates memory block equivalent to num * size . The function returns a pointer to the beginning of the allocated storage area in memory. The important difference between malloc and calloc function is that calloc initializes all bytes in the allocation block to zero and the allocated memory may/may not be contiguous.
calloc function is used to reserve space for dynamic arrays. Has the following form.

void * calloc (size_t n, size_t size);

Number of elements in the first argument specifies the size in bytes of one element to the second argument. A successful partitioning, that address is returned, NULL is returned on failure.
For example, an int array of 10 elements can be allocated as follows.

int * array = (int *) calloc (10, sizeof (int));

Note that this function can also malloc, written as follows.

int * array = (int *) malloc (sizeof (int) * 10);
However, the malloc function, whereas the area reserved to the states that are undefined, the area allocated by the calloc function contains a 0. In fact, the calloc function is internally may be a function that calls malloc. After securing function by malloc, the area is filled with 0.
            

            ptr = malloc(10 * sizeof(int));          
             ptr = calloc(10, sizeof(int));

 realloc()

With the function realloc, you can change the size of the allocated area once. Has the following form.
void * realloc (void * ptr, size_t size);

The first argument specifies the address of an area that is currently allocated to the size in bytes of the modified second argument. Change the size, the return value is returned in re-allocated address space. Otherwise it returns NULL.

Size may be smaller but larger than the original. If you have small, reduced what was written in part will be inaccessible. If you increase the portion of the region will remain an indefinite increase.

The address of the source address changed, but the same could possibly be different, even if the different areas of the old style, because it is automatically released in the function realloc, for the older areas it is not necessary to call the free function. However, if the function fails and returns NULL, realloc, the older area is to remain still valid. Therefore, the first pointer argument of the function realloc, both can be NULL pointer return value is not returned.

# Include
int main (void)
{
int * p1, * p2;
p1 = (int *) calloc (5, sizeof (int)); /* number of elements in an array of type 5 int */
/ * To do something * /
p2 = (int *) realloc (p1, sizeof (int)); * / re-acquire the space of one type / * int
if (p2 == NULL) * / check if successful * /
{
free (p1); if it fails to get re-/ *, the region remains valid since the original * / to free myself
return 0;
}
p1 = NULL; safety measure * /. p1 is realloc () because it is released inside, / * Keep assigning NULL to clear the other can not use / * To do something * /
free (p2);
return 0;
}

The realloc function is a very feature-rich functions. This is not the pros, cons and rather may be better. For example, if a NULL pointer to the first argument passed to the malloc function with the same behavior as the size specified in the second argument. Meanwhile, the second argument to zero, the operation to free the space pointed to by the free function specified in the first argument.

In other words, whatever the arguments, it is the sister supposed to mean something to the result, which may not have to be an error with the error should really be something. In particular, even in very common use, such as the following:

char * p2 = realloc (p1, size);

Happened, if the variable size is zero, this is not the same behavior as the function becomes free. If it is NULL p1, is the handling function malloc. NULL and 0 respectively when and what behavior is undefined.
In addition, the pointer argument to realloc function first must point to a secure area using one of the functions malloc / calloc / realloc (if a NULL pointer may be, in which case the above equal to the malloc function and so on).


Quite complex because, you have put a sample implementation of realloc function to aid understanding.

void * realloc (void * ptr, size_t size)
{
char * p;
if (ptr == NULL)
{
return malloc (size); if the first argument is NULL / * * / function which works the same as malloc }
if (size == 0)
{
free (ptr); second argument is 0 / * * / function which works the same as free
return NULL; * / return NULL because no new areas to be reserved * /
}

p = malloc (size); using the function / * malloc, * / a space equivalent to the size of the newer
if (p == NULL) {return NULL; if the function fails} / * malloc, return NULL. The original area * / remain
memcpy (p, ptr, size); the data in the source area / * * / to be copied to newly allocated space
free (ptr); source area / * the * / to be released
return p; * / return the address of the beginning of a new space * / }
Here are the points you need to remember.

•    The contents of the object will remain unaltered up to the lesser of the new and old sizes.
•    If the new size of the memory object would require movement of the object, the space for the previous 
instantiation of the object is freed.

•    If the new size is larger, the contents of the newly allocated portion of the object are unspecified.
•    If size is zero and ptr isn't a null pointer, the object pointed to is freed.
•    If the space can't be allocated, the object remains unaltered.
•    If ptr is a null pointer, realloc() acts like malloc() for the specified size.

This chapter will explain dynamic memory management in C. The C programming language provides several functions for memory allocation and management. These functions can be found in the <stdlib.h> header file.

Allocating Memory Dynamically

While doing programming, if you are aware about the size of an array, then it is easy and you can define it as an array. For example to store a name of any person, it can go max 100 characters so you can define something as follows:

char name[100];

But now let us consider a situation where you have no idea about the length of the text you need to store, for example you want to store a detailed description about a topic. Here we need to define a pointer to character without defining how much memory is required and later based on requirement we can allocate memory as shown in the below example:

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

int main()
{
   char name[100];
   char *description;

   strcpy(name, "Zara Ali");

   /* allocate memory dynamically */
   description = malloc( 200 * sizeof(char) );
   if( description == NULL )
   {
      fprintf(stderr, "Error - unable to allocate required memory\n");
   }
   else
   {
      strcpy( description, "star");
   }
   printf("Name = %s\n", name );
   printf("Description: %s\n", description );
}
When the above code is compiled and executed, it produces the following result.
Same progam can be written using calloc() only thing you need to replace malloc with calloc as follows:
calloc(200, sizeof(char));
So you have complete control and you can pass any size value while allocating memory unlike arrays where once you defined the size can not be changed.

     Resizing and Releasing Memory

When your program comes out, operating system automatically release all the memory allocated by your program but as a good practice when you are not in need of memory anymore then you should release that memory by calling the function free().

Alternatively, you can increase or decrease the size of an allocated memory block by calling the function realloc(). Let us check the above program once again and make use of realloc() and free() functions:


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

int main()
{
   char name[100];
   char *description;

   strcpy(name, "Zara Ali");

   /* allocate memory dynamically */
   description = malloc( 30 * sizeof(char) );
   if( description == NULL )
   {
      fprintf(stderr, "Error - unable to allocate required memory\n");
   }
   else
   {
      strcpy( description, "Zara ali a DPS student.");
   }
   /* suppose you want to store bigger description */
   description = realloc( description, 100 * sizeof(char) );
   if( description == NULL )
   {
      fprintf(stderr, "Error - unable to allocate required memory\n");
   }
   else
   {
      strcat( description, "She is in class 10th");
   }
  
   printf("Name = %s\n", name );
   printf("Description: %s\n", description );

   /* release memory using free() function */
   free(description);
}

Kindly Bookmark this Post using your favorite Bookmarking service:
Technorati Digg This Stumble Stumble Facebook Twitter
YOUR ADSENSE CODE GOES HERE

0 comments:

Post a Comment

Dont Forget for Commets

 

| C programing tutorials © 2009. All Rights Reserved | Template Style by My Blogger Tricks .com | Design by Brian Gardner | Back To Top |