跳到主要内容

C++ free() 函数

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 << "输入 5 个整数" << endl;

for (int i=0; i<5; i++)
{
// *(ptr+i) 可以被替换为 ptr[i]
cin >> *(ptr+i);
}
cout << endl << "用户输入的值" << endl;

for (int i=0; i<5; i++)
{
cout << *(ptr+i) << " ";
}
free(ptr);

/* 在 ptr 被释放后打印一个垃圾值 */
cout << "垃圾值" << 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 <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;

int main()
{
float *ptr;
ptr = (float*) calloc(1,sizeof(float));
*ptr = 5.233;

cout << "释放前" << endl;
cout << "地址 = " << ptr << endl;
cout << "值 = " << *ptr << endl;

free(ptr);

cout << "释放后" << endl;
/* ptr 保持不变,*ptr 发生变化 */
cout << "地址 = " << ptr << endl;
cout << "值 = " << *ptr << endl;
return 0;
}
```当你运行程序时,输出将是:

```cpp
释放前
地址 = 0x6a1530
= 5.233
释放后
地址 = 0x6a1530
= 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 << "重新分配前: " << ptr << endl;

/* 重新分配内存 */
ptr = (char*) realloc(ptr,20);
strcpy(ptr,"Hello, Welcome to C++");
cout << "重新分配后: " <<ptr << endl;

free(ptr);
/* 在 ptr 被释放后打印一个垃圾值 */
cout << endl << "垃圾值: " << ptr;

return 0;
}

当你运行程序时,输出将是:

重新分配前: Hello C++
重新分配后: Hello, Welcome to C++
垃圾值: @↨/

示例 4:free() 函数的其他情况

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

int main()
{
int x = 5;
int *ptr1 = NULL;

/* 不使用 calloc、malloc 或 realloc 分配内存 */
int *ptr2 = &x;
if(ptr1)
{
cout << "指针非空" << endl;
}
else
{
cout << "指针为空" << endl;
}

/* 无操作 */
free(ptr1);
cout << *ptr2;

/* 如果执行 free(ptr2),将导致运行时错误 */
// free(ptr2);

return 0;
}

当你运行程序时,输出将是:

指针为空
5