{{keywords>wiki library source code example reference}}
====== free ======
#include
void free(void *ptr);
=== description ===
The free() function shall cause the space pointed to by ptr to be deallocated; that is, made available for further allocation.\\
If ptr is a null pointer, no action shall occur. Otherwise, if the argument does not match a pointer earlier returned by \\
the calloc(), malloc(), posix_memalign(), realloc(), or strdup() function, or if the space has been deallocated by a call\\
to free() or realloc(), the behavior is undefined.\\
\\
Any use of a pointer that refers to freed space results in undefined behavior.\\
=== return value ===
The free() function shall not return a value.
===== free c Sourcecode Example =====
/*
* free example code
* http://code-reference.com/c/stdlib.h/free
*/
#include /* including standard library */
//#include /* uncomment this for Windows */
#include
int testit ( int *x )
{
if (x != NULL) {
printf("allocation of memory was successfully.\n");
}
else {
printf("allocation of memory failed.\n");
}
return 0;
}
int main ( void )
{
int *buffer;
printf("set buffer to 100 * sizeof(int)\n");
buffer = (int*) malloc (100*sizeof(int));
testit(buffer);
printf("set buffer to 1000 * sizeof(int)\n");
buffer = (int*) calloc (1000,sizeof(int));
testit(buffer);
printf("set buffer to 10 * sizeof(int)\n");
buffer = (int*) realloc (buffer,10*sizeof(int));
testit(buffer);
printf("try to free the buffer\n");
free (buffer);
return 0;
}
==== Output ====
user@host:~$ ./free
set buffer to 100 * sizeof(int)
allocation of memory was successfully.
set buffer to 1000 * sizeof(int)
allocation of memory was successfully.
set buffer to 10 * sizeof(int)
allocation of memory was successfully.
try to free the buffer