Everything

free


Memory release

[Classification]

Standard library

[Syntax]

#include <stdlib.h>

void free(void *ptr);

[Description]

This function releases the area pointed to by ptr so that this area is subsequently available for allocation. The area that was acquired by calloc, malloc, or realloc must be specified for ptr.

[Example]

#include    <stdlib.h>
typedef struct {
    double  d[3];
    int     i[2];
} s_data;
int func(void) {
    s_data   *buf;
    if((buf = calloc(40, sizeof(s_data))) == NULL)  /*allocate an area for 40 s_data*/
        return(1);
      :
    free(buf);                                      /*release the area*/
    return(0);
}

 

If one of the following operations is performed when using the library for the security facility, the __heap_chk_fail function is called.

-

The pointer to an area other than that allocated by calloc, malloc, or realloc is passed to free or realloc.

-

The pointer to an area released by free is passed again to free or realloc.

-

A value is written to up to four bytes before and after the area allocated by calloc, malloc, or realloc and the pointer to that area is passed to free or realloc.

The __heap_chk_fail function needs to be defined by the user and it describes the processing to be executed when an error occurs in management of dynamic memory.

Note the following points when defining the __heap_chk_fail function.

-

The only possible type of return value is void and the __heap_chk_fail function does not have formal parameters.

-

Do not define the function as static.

-

Corruption of heap memory area should not be detected recursively in the __heap_chk_fail function.

-

PIC (see "8.6 PIC/PID Facility") must not be performed for the __heap_chk_fail function.

The calloc, malloc, and realloc functions for the security facility allocate four extra bytes before and after each allocated area for the purpose of detecting writing to addresses outside the allocated area. This consumes more heap memory area than with the usual functions.

#include <stdlib.h>
 
void sub(int *ip) {
    ...
    free(ip);
}
 
int func(void) {
    int *ip;
    if ((ip = malloc(40 * sizeof(int))) == NULL)
        if ((ip = malloc(10 * sizeof(int))) == NULL) return(1);
        else sub(ip); /* First appearance of free */
    else
        ...
    free(ip); /* Second appearance of free */
    return(0);
}
 
void __heap_chk_fail(void) {
    /* Processing when corruption of heap memory area is detected */
}