首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

覆盖全局的operator new,什么时候会分配0个字节?该怎么处理

2012-05-16 
覆盖全局的operator new,什么时候会分配0个字节?网上对于全局operator new的重载一般都说有6种形式,最基本

覆盖全局的operator new,什么时候会分配0个字节?
网上对于全局operator new的重载一般都说有6种形式,最基本的一种是:

C/C++ code
void* operator new( size_t size ){    cout<<size<<endl;    if(0 == size){//什么时候会分配0字节? 似乎不可能啊         return 0;    }    void *p = malloc(size);    return p;}


什么时候调用一个new操作符号,可能传入的参数是0? 有这样的情况吗?
我怎么觉得这个判断有点多余啊。

[解决办法]
估计是为了把malloc的这个bug给修复了吧。看下面这个代码,居然malloc了0字节的内存。只是在上面的函数中能够防止这个误会了
C/C++ code
#include <stdio.h>#include <stdlib.h>int main(){    int *p=NULL;    p = (int *)malloc(0);    if (p==NULL)    {        printf("OK\n");        return -1;    }    else    {        printf("ERROR\n");        free(p);    }    return 0;}
[解决办法]
这是网上写的,又不是C++委员会写的,信他得不到永生。

热点排行