📅  最后修改于: 2020-09-25 08:50:03             🧑  作者: Mango
C++中的free() 函数释放先前使用calloc,malloc或realloc函数分配的内存块,使其可用于进一步分配。
free() 函数不会更改指针的值,也就是说,它仍指向相同的内存位置。
void free(void *ptr);
该函数在
free() 函数返回任何内容。它只是使内存块对我们可用。
#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<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
#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;
}
运行该程序时,输出为:
Before freeing
Address = 0x6a1530
Value = 5.233
After freeing
Address = 0x6a1530
Value = 9.7429e-039
#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: " <
运行该程序时,输出为:
Before reallocating: Hello C++
After reallocating: Hello, Welcome to C++
Garbage Value: @↨/
#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;
}
运行该程序时,输出为:
Pointer is Null
5