c++ 中的malloc、 realloc和new

参考链接:
https://www.cnblogs.com/zhanjxcom/p/5766844.html
http://www.runoob.com/cprogramming/c-function-realloc.html

动态内存的申请与释放必须配对,程序中malloc与free的使用次数一定要相同,否则肯定有错误(new/delete同理)

malloc和new的效果相似,但是如果想追加内存,则必须使用realloc函数。

#include 
#include 
#include 
using namespace std;


int main()
{
    char *p;
    p = (char *)malloc(10*sizeof(char));
    cout << "p: " << sizeof(p) << endl;
    //使用malloc函数后,一般要使用memset讲内存初始化	
    memset(p,0,10*sizeof(char));

    strcpy(p,"come on");
    cout << "p: " << p << endl;

    p =(char *)realloc(p,20*sizeof(char));
    cout << "p: " << sizeof(p) << endl;

    strcat(p,",baby!");
    cout << "p: " << p << endl;

    free(p);


    p=new char[10];
    strcpy(p,"come on");
    cout << "p: " << p << endl;
    p =(char *)realloc(p,20*sizeof(char));
    cout << "p: " << sizeof(p) << endl;

    strcat(p,",baby!");

    cout << "p: " << p << endl;
    delete[] p;

    return 0;

}

你可能感兴趣的:(c/c++)