2013-07-01 74 views
0

下面的程序:malloc成功或失敗了嗎?

/* 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 

如果分配失敗,爲什麼我得到一個非空指針?

+5

嗯..在這兩種情況下,您正在打印「分配成功」。 –

+0

Dooh ................... – jww

+0

你應該回答這個問題,所以我可以給你點。 – jww

回答

4

在這兩種情況下,您正在打印「分配成功」,這可能有點誤導。

+0

謝謝。我將它留給子孫後代...... – jww

+0

你應該接受答案 –

+0

謝謝艾哈邁德。所以我不會立即接受答案。顯然有10或15分鐘的等待期。 – jww