realloc:
void * realloc ( void * ptr, size_t size );
Reallocate memory block
In case that ptr is NULL, the function behaves exactly as MALLOC, assigning a new block of size bytes and returning a pointer to the beginning of it.
eg. realloc (NULL, sizeof(int));
In case that the size is 0, the memory previously allocated in ptr is deallocated as if a call to free was made, and a NULL pointer is returned.
Showing posts with label free. Show all posts
Showing posts with label free. Show all posts
Thursday, January 28, 2010
Wednesday, January 6, 2010
Why a programmer need to take care of freeing the memory?
Why a programmer need to take care of freeing the memory?
If you have a subroutine like this
int subroutine(int param){
char example_variable [200];
whatever the routine does....
}
is necessary to release the memory used by the variable example_variable??? or is this automatically released when the variable get out of scope???
variables are created in different spaces within a program.
the example[100] variable would be created within a stack which would be deleted as soon as the program terminates so the programmer doesn't need to take care of freeing that. but any address dynamically obtained is obtained from the heap which is a pool of memory of all the programs running and not specific to one. so a programmer needs to take care of freeing or deleting (basically returning the space back to the pool) when the purpose of that variable is served and no longer required.
If you have a subroutine like this
int subroutine(int param){
char example_variable [200];
whatever the routine does....
}
is necessary to release the memory used by the variable example_variable??? or is this automatically released when the variable get out of scope???
variables are created in different spaces within a program.
the example[100] variable would be created within a stack which would be deleted as soon as the program terminates so the programmer doesn't need to take care of freeing that. but any address dynamically obtained is obtained from the heap which is a pool of memory of all the programs running and not specific to one. so a programmer needs to take care of freeing or deleting (basically returning the space back to the pool) when the purpose of that variable is served and no longer required.
malloc,calloc,realloc and free
malloc(),calloc(),realloc() & free():
malloc (memory allocation) is used to dynamically allocate memory at run time. Possible uses for this function are:
Read records of an unknown length.
Read an unknown number of database records.
Link lists.
The simplest way to reserve memory is to code something like:
main()
{
char string[1000];
strcpy (string, "Some text");
}
The example above has two problems:
If the data is less than 1000 bytes we are wasting memory.
If the data is greater than 1000 bytes the program is going to crash.
The 1000 bytes are reserved throught out the life of the program. If this was a long running program that rarely used the memory, it would again be wasteful.
malloc allows us to allocate exactly the correct amount of memory and with the use of free only for the time it is required.
Library: stdlib.h
Prototype: void *malloc(size_t size);
Syntax: char * String;
String = (char *) malloc(1000);
Looking at the example syntax above, 1000 bytes are reserved and the pointer String points to the first byte. The 1000 bytes are NOT initialized by malloc. If the memory is NOT available, a NULL pointer is returned.
The calloc() Function
The standard C library declares the function calloc() in as follows:
void *calloc(size_t elements, size_t sz);
calloc() allocates space for an array of elements, each of which occupies sz bytes of storage. The space of each element is initialized to binary zeros. In other words, calloc() is similar to malloc(), except that it handles arrays of objects rather than a single chunk of storage and that it initializes the storage allocated. The following example allocates an array of 100 int's using calloc():
int * p = (int*) calloc (100, sizeof(int));
Remember that in C++, you have better alternatives to calloc() and malloc(), namely new and new [], and that these C functions should only be used for allocating POD (Plain Old Data) objects; never class objects. However, if you're using C or maintaining legacy C code, you might get across this function.
realloc:
void * realloc ( void * ptr, size_t size );
Reallocate memory block
The size of the memory block pointed to by the ptr parameter is changed to the size bytes, expanding or reducing the amount of memory available in the block.
The function may move the memory block to a new location, in which case the new location is returned. The content of the memory block is preserved up to the lesser of the new and old sizes, even if the block is moved. If the new size is larger, the value of the newly allocated portion is indeterminate.
In case that ptr is NULL, the function behaves exactly as malloc, assigning a new block of size bytes and returning a pointer to the beginning of it.
In case that the size is 0, the memory previously allocated in ptr is deallocated as if a call to free was made, and a NULL pointer is returned.
Return Value:A pointer to the reallocated memory block, which may be either the same as the ptr argument or a new location.
The type of this pointer is void*, which can be cast to the desired type of data pointer in order to be dereferenceable.
If the function failed to allocate the requested block of memory, a NULL pointer is returned.
/* realloc example: rememb-o-matic */
#include < stdio.h >
#include < stdlib.h >
int main ()
{
int input,n;
int count=0;
int * numbers = NULL;
do {
printf ("Enter an integer value (0 to end): ");
scanf ("%d", &input);
count++;
numbers = (int*) realloc (numbers, count * sizeof(int));
if (numbers==NULL)
{ puts ("Error (re)allocating memory"); exit (1); }
numbers[count-1]=input;
} while (input!=0);
printf ("Numbers entered: ");
for ( n=0; n < count; n++) printf ("%d ",numbers[n]); free (numbers); return 0; } The program prompts the user for numbers until a zero character is entered. Each time a new value is introduced the memory block pointed by numbers is increased by the size of an int. free:
Example
/* free example */
#include
#include
int main ()
{
int * buffer1, * buffer2, * buffer3;
buffer1 = (int*) malloc (100*sizeof(int));
buffer2 = (int*) calloc (100,sizeof(int));
buffer3 = (int*) realloc (buffer2,500*sizeof(int));
free (buffer1);
free (buffer3);
return 0;
}
This program has no output. Just demonstrates some ways to allocate and free dynamic memory using the cstdlib functions.
Also, check out Free ISTQB Training Material here
www.testing4success.com - Application QA/Testing Mobile App QA/Testing Web Testing Training
Iphone App QA Android App QA Web QA
malloc (memory allocation) is used to dynamically allocate memory at run time. Possible uses for this function are:
Read records of an unknown length.
Read an unknown number of database records.
Link lists.
The simplest way to reserve memory is to code something like:
main()
{
char string[1000];
strcpy (string, "Some text");
}
The example above has two problems:
If the data is less than 1000 bytes we are wasting memory.
If the data is greater than 1000 bytes the program is going to crash.
The 1000 bytes are reserved throught out the life of the program. If this was a long running program that rarely used the memory, it would again be wasteful.
malloc allows us to allocate exactly the correct amount of memory and with the use of free only for the time it is required.
Library: stdlib.h
Prototype: void *malloc(size_t size);
Syntax: char * String;
String = (char *) malloc(1000);
Looking at the example syntax above, 1000 bytes are reserved and the pointer String points to the first byte. The 1000 bytes are NOT initialized by malloc. If the memory is NOT available, a NULL pointer is returned.
The calloc() Function
The standard C library declares the function calloc() in as follows:
void *calloc(size_t elements, size_t sz);
calloc() allocates space for an array of elements, each of which occupies sz bytes of storage. The space of each element is initialized to binary zeros. In other words, calloc() is similar to malloc(), except that it handles arrays of objects rather than a single chunk of storage and that it initializes the storage allocated. The following example allocates an array of 100 int's using calloc():
int * p = (int*) calloc (100, sizeof(int));
Remember that in C++, you have better alternatives to calloc() and malloc(), namely new and new [], and that these C functions should only be used for allocating POD (Plain Old Data) objects; never class objects. However, if you're using C or maintaining legacy C code, you might get across this function.
realloc:
void * realloc ( void * ptr, size_t size );
Reallocate memory block
The size of the memory block pointed to by the ptr parameter is changed to the size bytes, expanding or reducing the amount of memory available in the block.
The function may move the memory block to a new location, in which case the new location is returned. The content of the memory block is preserved up to the lesser of the new and old sizes, even if the block is moved. If the new size is larger, the value of the newly allocated portion is indeterminate.
In case that ptr is NULL, the function behaves exactly as malloc, assigning a new block of size bytes and returning a pointer to the beginning of it.
In case that the size is 0, the memory previously allocated in ptr is deallocated as if a call to free was made, and a NULL pointer is returned.
Return Value:A pointer to the reallocated memory block, which may be either the same as the ptr argument or a new location.
The type of this pointer is void*, which can be cast to the desired type of data pointer in order to be dereferenceable.
If the function failed to allocate the requested block of memory, a NULL pointer is returned.
/* realloc example: rememb-o-matic */
#include < stdio.h >
#include < stdlib.h >
int main ()
{
int input,n;
int count=0;
int * numbers = NULL;
do {
printf ("Enter an integer value (0 to end): ");
scanf ("%d", &input);
count++;
numbers = (int*) realloc (numbers, count * sizeof(int));
if (numbers==NULL)
{ puts ("Error (re)allocating memory"); exit (1); }
numbers[count-1]=input;
} while (input!=0);
printf ("Numbers entered: ");
for ( n=0; n < count; n++) printf ("%d ",numbers[n]); free (numbers); return 0; } The program prompts the user for numbers until a zero character is entered. Each time a new value is introduced the memory block pointed by numbers is increased by the size of an int. free:
Example
/* free example */
#include
#include
int main ()
{
int * buffer1, * buffer2, * buffer3;
buffer1 = (int*) malloc (100*sizeof(int));
buffer2 = (int*) calloc (100,sizeof(int));
buffer3 = (int*) realloc (buffer2,500*sizeof(int));
free (buffer1);
free (buffer3);
return 0;
}
This program has no output. Just demonstrates some ways to allocate and free dynamic memory using the cstdlib functions.
Also, check out Free ISTQB Training Material here
www.testing4success.com - Application QA/Testing Mobile App QA/Testing Web Testing Training
Iphone App QA Android App QA Web QA
Avoid Using malloc() and free() in C++
Avoid Using malloc() and free() in C++
The use of malloc() and free() functions in a C++ file is not recommended and is even dangerous:
1. malloc() requires the exact number of bytes as an argument whereas new calculates the size of the allocated object automatically. By using new, silly mistakes such as the following are avoided:
long * p = malloc(sizeof(short)); //p originally pointed to a short;
//changed later (but malloc's arg was not)
2. malloc() does not handle allocation failures, so you have to test the return value of malloc() on each and every call. This tedious and dangerous function imposes performance penalty and bloats your .exe files. On the other hand, new throws an exception of type std::bad_alloc when it fails, so your code may contain only one catch(std::bad_alloc) clause to handle such exceptions.
3. As opposed to new, malloc() does not invoke the object's constructor. It only allocates uninitialized memory. The use of objects allocated this way is undefined and should never occur. Similarly, free() does not invoke its object's destructor.
The use of malloc() and free() functions in a C++ file is not recommended and is even dangerous:
1. malloc() requires the exact number of bytes as an argument whereas new calculates the size of the allocated object automatically. By using new, silly mistakes such as the following are avoided:
long * p = malloc(sizeof(short)); //p originally pointed to a short;
//changed later (but malloc's arg was not)
2. malloc() does not handle allocation failures, so you have to test the return value of malloc() on each and every call. This tedious and dangerous function imposes performance penalty and bloats your .exe files. On the other hand, new throws an exception of type std::bad_alloc when it fails, so your code may contain only one catch(std::bad_alloc) clause to handle such exceptions.
3. As opposed to new, malloc() does not invoke the object's constructor. It only allocates uninitialized memory. The use of objects allocated this way is undefined and should never occur. Similarly, free() does not invoke its object's destructor.
Subscribe to:
Posts (Atom)