以下程序:

/* gcc -O1 -g3 -std=c99 -Wall -Wextra -m32 t.c -o t.exe */

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[]) {

    static const unsigned int MALLOC_SIZE = 0x80000000;
    int ret = -1;

    unsigned char * ptr = malloc(MALLOC_SIZE);
    if(ptr) {
        printf("Allocation succeeded\n");
        printf("%02X … %02X\n", ptr[0], ptr[MALLOC_SIZE - 1]);
        free(ptr);
        ret = 0;
    } else {
        printf("Allocation succeeded\n");
        ret = 1;
    }
    return ret;
}

$ lipo -info t.exe
Non-fat file: t.exe is architecture: i386

产生以下输出:
$ ./t.exe
t.exe(19449) malloc: *** mmap(size=2147483648) failed (error code=12)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
Allocation succeeded

如果分配失败,为什么要返回一个非空指针?

最佳答案

无论哪种情况,您都要打印“分配成功”,这可能会有点误导。

关于c - malloc是成功还是失败?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17396842/

10-11 23:07
查看更多