C++ 中的 free() 函数用于释放之前使用 calloc、malloc 或 realloc 函数分配的内存块,使其可用于进一步分配。
free() 函数不会改变 指针 的值,也就是说,它仍然指向同一内存位置。
free() 原型
void free(void *ptr);
该函数定义在 <cstdlib> 头文件中。
free() 参数
- ptr: 指向之前使用 malloc、calloc 或 realloc 分配的内存块的指针。该指针可以为 null,或者可能不指向由 calloc、malloc 或 realloc 函数分配的内存块。
- 如果 ptr 为 null,free() 函数不做任何操作。
- 如果 ptr 不指向由 calloc、malloc 或 realloc 函数分配的内存块,则会导致未定义行为。
free() 返回值
free() 函数不返回任何值。它只是使内存块可供我们使用。
示例 1:free() 函数如何与 malloc() 一起工作?
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int *ptr;
ptr = (int*) malloc(5*sizeof(int));
cout << "Enter 5 integers" << endl;
for (int i=0; i<5; i++)
{
// *(ptr+i) can be replaced by ptr[i]
cin >> *(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;
}
运行程序后,输出将是
Enter 5 integers 21 3 -10 -13 45 User entered value 21 3 -10 -13 45 Garbage Value 6690624 0 6685008 0 45
示例 2:free() 函数如何与 calloc() 一起工作?
#include <iostream>
#include <cstdlib>
#include <cstring>
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;
}
运行程序后,输出将是
Before freeing Address = 0x6a1530 Value = 5.233 After freeing Address = 0x6a1530 Value = 9.7429e-039
示例 3:free() 函数如何与 realloc() 一起工作?
#include <iostream>
#include <cstdlib>
#include <cstring>
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: " <<ptr << endl;
free(ptr);
/* prints a garbage value after ptr is free */
cout << endl << "Garbage Value: " << ptr;
return 0;
}
运行程序后,输出将是
Before reallocating: Hello C++ After reallocating: Hello, Welcome to C++ Garbage Value: @↨/
示例 4:free() 函数与其他情况
#include <iostream>
#include <cstdlib>
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;
}
运行程序后,输出将是
Pointer is Null 5