Under what circumstances can malloc return NULL?

前端 未结 9 1614
陌清茗
陌清茗 2020-12-23 14:17

It has never happened to me, and I\'ve programming for years now.

Can someone give me an example of a non-trivial program in which malloc will actually

相关标签:
9条回答
  • 2020-12-23 15:03

    Since you asked for an example, here's a program that will (eventually) see malloc return NULL:

    perror();void*malloc();main(){for(;;)if(!malloc(999)){perror(0);return 0;}}
    

    What? You don't like deliberately obfuscated code? ;) (If it runs for a few minutes and doesn't crash on your machine, kill it, change 999 to a bigger number and try again.)

    EDIT: If it doesn't work no matter how big the number is, then what's happening is that your system is saying "Here's some memory!" but so long as you don't try to use it, it doesn't get allocated. In which case:

    perror();char*p;void*malloc();main(){for(;;){p=malloc(999);if(p)*p=0;else{perror(0);return 0;}}
    

    Should do the trick. If we can use GCC extentions, I think we can get it even smaller by changing char*p;void*malloc(); to void*p,*malloc(); but if you really wanted to golf you'd be on the Code Golf SE.

    0 讨论(0)
  • 2020-12-23 15:06

    Yes.

    Just try to malloc more memory than your system can provide (either by exhausting your address space, or virtual memory - whichever is smaller).

    malloc(SIZE_MAX)
    

    will probably do it. If not, repeat a few times until you run out.

    0 讨论(0)
  • 2020-12-23 15:11

    Pick any platform, though embedded is probably easier. malloc (or new) a ton of RAM (or leak RAM over time or even fragment it by using naive algorithms). Boom. malloc does return NULL for me on occasion when "bad" things are happening.

    In response to your edit. Yes again. Memory fragmentation over time can make it so that even a single allocation of an int can fail. Also keep in mind that malloc doesn't just allocate 4 bytes for an int, but can grab as much space as it wants. It has its own book-keeping stuff and quite often will grab 32-64 bytes minimum.

    0 讨论(0)
提交回复
热议问题