C – Free 2017-08-07T14:20:32+00:00

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 this function , 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.

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:

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.


Output :

Default values are :






Prev Next