c语言中free函数
C ++ free()函数 (C++ free() function)
free() function is a library function of cstdlib header. It is used to deallocate the dynamically allocated memory blocks (i.e. the memory blocks allocated by the malloc(), calloc(), or realloc() functions) so that the memory blocks can be used for further allocations. It accepts a parameter which should be the pointer to the allocated memory.
free()函数是cstdlib标头的库函数。 它用于取消分配动态分配的内存块(即,由malloc() , calloc()或realloc()函数分配的内存块),以便可以将这些内存块用于进一步的分配。 它接受一个参数,该参数应该是指向已分配内存的指针。
Note: If the pointer does not point to the dynamically allocated memory it causes undefined behavior and if it is a null pointer, free() function does nothing.
注意:如果指针未指向动态分配的内存,则它将导致未定义的行为;如果指针为空,则free()函数将不执行任何操作。
Syntax of free() function:
free()函数的语法:
C++11:
C ++ 11:
void free (void* ptr);
Parameter(s):
参数:
ptr – represents a pointer to the dynamically allocated memory blocks.
ptr –表示指向动态分配的内存块的指针。
Return value:
返回值:
The return type of this function is void, It does not return anything.
该函数的返回类型为void ,它不返回任何内容。
Example:
例:
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)
// 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;
}
Output
输出量
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
Reference: C++ free() function
参考: C ++ free()函数
翻译自: https://www.includehelp.com/cpp-tutorial/free-function-with-example.aspx
c语言中free函数