當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ free()用法及代碼示例

C++ free() 函數

free() 函數是 cstdlib 頭文件的庫函數。它用於釋放動態分配的內存塊(即由malloc()calloc(), 或者realloc()函數),以便內存塊可用於進一步分配。它接受一個參數,該參數應該是指向已分配內存的指針。

注意:如果指針不指向動態分配的內存,則會導致未定義行為,如果它是空指針,則 free() 函數不執行任何操作。

free() 函數的語法:

C++11:

    void free (void* ptr);

參數:

  • ptr– 表示指向動態分配的內存塊的指針。

返回值:

這個函數的返回類型是void, 它不返回任何東西。

例:

    Input:
    // number of elements
    n = 5;

    // Dynamically allocate memory using malloc()
    ptr = (int*)malloc(n * sizeof(int));

    Function call:
    // freeing memory
    free(ptr);

C++代碼演示free()函數的例子

// C++ code to demonstrate the example of
// free() function

#include <iostream>
#include <cstdlib>
using namespace std;

// main() section
int main()
{
    int* ptr; // pointer
    int n, i;

    cout << "Enter number of elements:";
    cin >> n;

    // Dynamically allocate memory using malloc()
    ptr = (int*)malloc(n * sizeof(int));

    // Check whether memory is allocated or not
    if (ptr == NULL) {
        cout << "Memory not allocated.." << endl;
        exit(EXIT_FAILURE);
    }
    else {
        cout << "Memory created..." << endl;

        // input array elements
        for (i = 0; i < n; ++i) {
            cout << "Enter element " << i + 1 << ":";
            cin >> ptr[i];
        }

        // Print the array elements
        cout << "The array elements are:";
        for (i = 0; i < n; ++i) {
            cout << ptr[i] << " ";
        }
        cout << endl;

        // freeing the memory
        free(ptr);
    }

    return 0;
}

輸出

Enter number of elements:5
Memory created...
Enter element 1:10
Enter element 2:20
Enter element 3:30
Enter element 4:40
Enter element 5:50
The array elements are:10 20 30 40 50

參考:C++ free() 函數



相關用法


注:本文由純淨天空篩選整理自 free() Function with Example in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。