Malloc失败了,伐木,这不是愚蠢的吗?

时间:2013-11-22 00:23:49

标签: malloc

这是代码,这不是没有意义的吗?

  unsigned char * rngBuf = malloc(nBytes);
    if(!rngBuf) {
        DDLogError(@"Unable to allocate buffer for random bytes.");
        [self displayHUDMessage:@"Memory Error."];
        return;
    }

如果malloc失败,为什么记录或显示hud会成功?

处理这种情况的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

只有从堆中显示错误需要nbytes或更多内存(来自堆栈,静态或带引号的字符串,或编译时解析的字符串宏,如 FILE 功能)。

我不熟悉您的API,但我确保在我的代码中使用静态分配的打印缓冲区。这是一个例子。

//  ... file management data structures...
typedef struct {
    FILE     *fp;
    size_t   knt;           //  record counter for use when needed
    ULLNG    bytes;         //  total number of bytes written to .fp file handle
    char     name[128];
    char     mode_str[8];   
} FILE_DESC, *pFILE_DESC;

typedef struct {
    FILE_DESC   *fargs; // for the price of a FILE pointer we get all the details :)
    size_t      bytes;
    char        buff[1<<20];
} SMART_PRN_BUFF, pSMART_PRN_BUFF;
// ---- allocate 4 static/global smart write-buffers here
static  SMART_PRN_BUFF  FiPrn[4];

与main()顶部附近的初始化程序配对,如...

FILE_DESC   File[4] = {{NULL,0,0,"","w+t"},{NULL,0,0,"","w+t"},{NULL,0,0,"","r+b"}, {NULL,0,0,"","w"}};


printf("\nProcessing %i file names in \n%s", argc -1, argv[0]);
for(int i=0; i<argc; i++) {
    if(NULL != argv[i+1])   {
        strcpy(File[i].name, argv[i+1]);
        File[i].fp = fopen(File[i].name, File[i].mode_str);
        if(NULL==File[i].fp) {
            printf("\nFile %s could not be opened in %s mode at line %i in %s\n--- ABORTING PROGRAM ---\n\n",
                    File[i].name, File[i].mode_str, __LINE__, __FILE__);
            exit(EXIT_FAILURE);
        } else {
            printf("\nFile %s opened in %s mode", File[i].name, File[i].mode_str);
        }
    }
    FiPrn[i].fargs = &File[i];
}

用法就像......

FiPrn[ERR].bytes += sprintf(FiPrn[ERR].buff, 
        "\nSize of FiPrn structure is %llu", (ULLNG)sizeof(FiPrn));
WriteToFile(&FiPrn[ERR]);

您可能已经注意到,我必须使用printf()vs sprintf()直到我打开文件并写入它们,但静态内存被分配为SMART_PRN_BUFF.buff [1&lt;&lt; 20],在我尝试打开他们要写入的文件之前,我为这里配置的4个文件中的每个文件提供了1兆字节。

所以我完全有信心我可以在几行之后打印来自malloc()和calloc()的回报,就像这样......

if(NULL == Sequencer)
    FiPrn[ERR].bytes += sprintf(FiPrn[ERR].buff + FiPrn[ERR].bytes,
    "\nCalloc() for Sequencer returned %p at line %i in file %s in function %s()\n",STD_ERR(Sequencer));

其中STD_ERR()是一个宏,可以帮助确保代码发出统一的错误消息,就像这样......

#define STD_ERR(rtn) rtn,__LINE__,__FILE__,__FUNCTION__ // uniform error handling