0% found this document useful (0 votes)
65 views

Malloc

The malloc() function dynamically allocates memory at runtime by allocating a specified number of bytes and returning a pointer to that memory. It returns NULL if the memory allocation fails. The calloc() function allocates memory like malloc() but initializes all bytes to zero. The realloc() function changes the size of previously allocated memory, potentially moving it to a new location. The free() function releases memory allocated by malloc(), calloc(), or realloc() so it is available for future allocations.

Uploaded by

rock
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views

Malloc

The malloc() function dynamically allocates memory at runtime by allocating a specified number of bytes and returning a pointer to that memory. It returns NULL if the memory allocation fails. The calloc() function allocates memory like malloc() but initializes all bytes to zero. The realloc() function changes the size of previously allocated memory, potentially moving it to a new location. The free() function releases memory allocated by malloc(), calloc(), or realloc() so it is available for future allocations.

Uploaded by

rock
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 13

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));

is just like this:

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


The following example illustrates the use of

calloc() function
.

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.

Here's an example ,learn this example and then try applying the same idea to write your own
programs.

Dynamic memmory allocation : free() function


Next, how to release the reserved area, which will use the function free. Has also been declared in
stdlib.h, which has the following form.
void free (void * ptr);
The argument specifies the address of a dynamically allocated area. You can then free up the
space. Specify an address outside the area should not be dynamically allocated. Also, if you specify
a NULL (or NULL if the same holds for a given pointer variable), the free function is guaranteed
to do nothing at all. In addition, if you try to re-release has already been freed space, so do not
know what would be, and should never be.
In addition, the space freed by the function free, guarantee that there is no data remains
intact. Thus, if once released, should not be accessing the same area.
So, an example program that uses functions malloc and free functions in practice.
# Include
# Include
int main (void)
{
int * p;
p = (int *) malloc (sizeof (int)); /* partitioning of type int */
if (p == NULL) * / failed to reserve area * /
{
printf ("Failed to allocate space for% d bytes", sizeof (int));
return 1;
}
* P = 150;
printf ("% d \ n", * p);
free (p); * / free area * /
return 0;
}

Critical applications such that the product should look into whether the failure to secure the
area. The method is to check the return value of malloc function as above. However, sample
programs, etc. are often omitted. Because such is unlikely to cause a shortage of modern
computer memory, that is not impossible.
In addition, the area again, once released, so that no access would, immediately after the function,
free, often take precautions to keep the pointer to NULL.
free (p);
p = NULL;
function free, attempt to free the same area more than once but should not, because nothing
happens when you specify a NULL, and that it's safe if you put it like this.
Of course, between the malloc() and the free(), you can do anything with the memory your twisted
little heart desires.
Let's see a simple example of the management of malloc and free:
# Include
int main ()
{
int bytes;
char * text;
printf ("How many bytes you want to book");
scanf ("% i", & bytes);
text = (char *) malloc (bytes);
/ * Check if the operation was successful * /
if (text)
{
printf ("Reserved memory:% i bytes =% i =% i Kbytes Mbytes \ n", bytes, bytes/1024, bytes /
(1024 * 1024 )) ;
printf ("The block starts at:% p \ n", text);
/ * Now free the memory * /
free (text);
}

else
printf ("Could not allocate memory \ n") ;
}
This example asks how much memory you want to book, if it can be shown how much memory is
reserved and where begins the block. Failure to achieve stated meniante the message: "Failed to
allocate memory."

Let's try this example reserving 1000 bytes:

How many bytes you want to book: 1000 Reserved Memory: 1000 bytes = 0 kb = 0 Mbytes The
block begins at: 90868

Try a few times by increasing the size of memory you want to book. If you 32Mbytes of RAM type
the following:

How many bytes you want to reserve: 32000000 Could not allocate memory Malloc has been
unable to reserve as much memory and returns (null) so we are warned that the operation could
not be performed.
Program:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy