C ++ free () - Стандартная библиотека C ++

Функция free () в C ++ освобождает блок памяти, ранее выделенный с помощью функций calloc, malloc или realloc, делая его доступным для дальнейшего выделения.

Функция free () в C ++ освобождает блок памяти, ранее выделенный с помощью функций calloc, malloc или realloc, делая его доступным для дальнейшего выделения.

Функция free () не изменяет значение указателя, то есть по-прежнему указывает на то же место в памяти.

бесплатный () прототип

 пусто бесплатно (void * ptr);

Функция определена в заголовочном файле.

free () Параметры

  • ptr: указатель на блок памяти, ранее выделенный с помощью malloc, calloc или realloc. Указатель может быть нулевым или не указывать на блок памяти, выделенный функциями calloc, malloc или realloc.
    • Если ptr равен нулю, функция free () ничего не делает.
    • Если ptr не указывает на блок памяти, выделенный функциями calloc, malloc или realloc, это вызывает неопределенное поведение.

free () Возвращаемое значение

Функция free () ничего не возвращает. Это просто делает блок памяти доступным для нас.

Пример 1. Как функция free () работает с malloc ()?

 #include #include using namespace std; int main() ( int *ptr; ptr = (int*) malloc(5*sizeof(int)); cout << "Enter 5 integers" << endl; for (int i=0; i> *(ptr+i); ) cout << endl << "User entered value"<< endl; for (int i=0; i<5; i++) ( cout << *(ptr+i) << " "; ) free(ptr); /* prints a garbage value after ptr is free */ cout << "Garbage Value" << endl; for (int i=0; i<5; i++) ( cout << *(ptr+i) << " "; ) return 0; )

Когда вы запустите программу, вывод будет:

 Введите 5 целых чисел 21 3-10-13 45 Введенное пользователем значение 21 3-10-13 45 Значение мусора 6690624 0 6685008 0 45

Пример 2: Как функция free () работает с calloc ()?

 #include #include #include using namespace std; int main() ( float *ptr; ptr = (float*) calloc(1,sizeof(float)); *ptr = 5.233; cout << "Before freeing" << endl; cout << "Address = " << ptr << endl; cout << "Value = " << *ptr << endl; free(ptr); cout << "After freeing" << endl; /* ptr remains same, *ptr changes*/ cout << "Address = " << ptr << endl; cout << "Value = " << *ptr << endl; return 0; )

Когда вы запустите программу, вывод будет:

 До освобождения Адрес = 0x6a1530 Значение = 5,233 После освобождения Адрес = 0x6a1530 Значение = 9,7429e-039

Пример 3: Как функция free () работает с realloc ()?

 #include #include #include using namespace std; int main() ( char *ptr; ptr = (char*) malloc(10*sizeof(char)); strcpy(ptr,"Hello C++"); cout << "Before reallocating: " << ptr << endl; /* reallocating memory */ ptr = (char*) realloc(ptr,20); strcpy(ptr,"Hello, Welcome to C++"); cout << "After reallocating: " < 

When you run the program, the output will be:

 Before reallocating: Hello C++ After reallocating: Hello, Welcome to C++ Garbage Value: @↨/

Example 4: free() function with other cases

 #include #include using namespace std; int main() ( int x = 5; int *ptr1 = NULL; /* allocatingmemory without using calloc, malloc or realloc*/ int *ptr2 = &x; if(ptr1) ( cout << "Pointer is not Null" << endl; ) else ( cout << "Pointer is Null" << endl; ) /* Does nothing */ free(ptr1); cout << *ptr2; /* gives a runtime error if free(ptr2) is executed*/ // free(ptr2); return 0; )

When you run the program, the output will be:

 Pointer is Null 5

Интересные статьи...