User Tools

Site Tools


Sidebar

Programming Reference/Librarys

Question & Answer

Q&A is closed







c:stdlib.h:free

free

    #include <stdlib.h>
    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 <stdio.h> /* including standard library */
//#include <windows.h> /* uncomment this for Windows */
 
#include <stdlib.h>
 
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
advertising
c/stdlib.h/free.txt · Last modified: 2014/10/12 05:22 by 201.141.133.121

Impressum Datenschutz