关于malloc的使用范例

    技术2026-08-27  8

    /***************************************     function:代码范例,malloc,free     author  : cinience@gmail.com ****************************************/

        const int memsize 1024;     char * p = NULL;       // 指针声明时,即初始化

        p = (char *)malloc(memsize);     assert ( NULL != p);   // 若要求不严格,可用if代替     memset(p,0,memsize);     /**         code;     **/     if ( NULL != p )       // 不再使用,释放空间,并赋NULL     {         free(p);         p = NULL;     }

    讨论: 1:关于delete p和 delete []p;     看了很多资料,有的说,后者可以替代前者,从理论上分析也是     但为了不必要的错误,和程序的严谨性,我们应该遵循:     new    对应   delete     new[]   对应  delete[]

    2,关于 malloc(0);     malloc(0)得到的是有效指针还是NULL都是不确定的     ,而且分配成功也不要使用,所以慎用

    C99标准(ISO/IEC 9899:1999 (E))上说:

    If the size of the space requested is zero, the behavior is implementationdefined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.

    最新回复(0)