C++中的自由函数是什么?
C/C++库函数void free(void *ptr)释放先前由对calloc、malloc或realloc的调用分配的内存。以下是free()函数的声明。
void free(void *ptr)
此函数采用一个指针ptr。这是之前通过malloc、calloc或realloc分配的内存块的指针,该内存块将被释放。如果传递一个空指针为参数,则不执行任何操作。
示例
#include <iostream> #include <cstdlib> #include <cstring> using namespace std; int main () { char *str; /* Initial memory allocation */ str = (char *) malloc(15); strcpy(str, "tutorialspoint"); cout << "String = "<< str <<", Address = "<< &str << endl; /* Reallocating memory */ str = (char *) realloc(str, 25); strcat(str, ".com"); cout << "String = "<< str <<", Address = "<< &str << endl; /* Deallocate allocated memory */ free(str); return(0); }
输出
String = tutorialspoint, Address = 0x22fe38 String = tutorialspoint.com, Address = 0x22fe38
广告