• [^] # Re: malloc peut retourner un pointeur nul

    Posté par (site web personnel) . En réponse au message pourquoi malloc peut échouer alors que linux utilise de la mémoire virtuelle. Évalué à 10. Dernière modification le 23 juillet 2019 à 13:46.

    Oui il fait chaud, mais soyons joueur :

    #include <stdlib.h>
    #include <stdio.h>
    int main()
    {
     size_t L = (size_t)20*1024;
     char *str = malloc(L);
     printf("str=%p\n", str);
    }
    $ gcc maloq.c
    $ size ./a.out 
     text data bss dec hex filename
     1617 608 8 2233 8b9 ./a.out
    $ ulimit -a
    core file size (blocks, -c) 0
    data seg size (kbytes, -d) unlimited
    scheduling priority (-e) 0
    file size (blocks, -f) unlimited
    pending signals (-i) 63452
    max locked memory (kbytes, -l) 16384
    max memory size (kbytes, -m) unlimited
    open files (-n) 1024
    pipe size (512 bytes, -p) 8
    POSIX message queues (bytes, -q) 819200
    real-time priority (-r) 0
    stack size (kbytes, -s) 8192
    cpu time (seconds, -t) unlimited
    max user processes (-u) 63452
    virtual memory (kbytes, -v) unlimited
    file locks (-x) unlimited
    $ ./a.out 
    str=0x5577f3ab2260
    # virtual memory
    $ sh -c 'ulimit -v 1000 ; ./a.out'
    Segmentation fault
    (...)
    $ sh -c 'ulimit -v 2359 ; ./a.out'
    Segmentation fault
    $ sh -c 'ulimit -v 2360 ; ./a.out'
    ./a.out: error while loading shared libraries: libc.so.6: failed to map segment from shared object
    (...)
    $ sh -c 'ulimit -v 4491 ; ./a.out'
    ./a.out: error while loading shared libraries: libc.so.6: failed to map segment from shared object
    $ sh -c 'ulimit -v 4492 ; ./a.out'
    str=(nil)
    (...)
    $ sh -c 'ulimit -v 4507 ; ./a.out'
    str=(nil)
    $ sh -c 'ulimit -v 4508 ; ./a.out'
    str=0x560591527260
    # stack size
    $ sh -c 'ulimit -s 11 ; ./a.out'
    Segmentation fault (core dumped)
    $ sh -c 'ulimit -s 12 ; ./a.out'
    str=0x55f97206f260
    # data seg size
    $ sh -c 'ulimit -d 19 ; ./a.out'
    Segmentation fault
    $ sh -c 'ulimit -d 20 ; ./a.out'
    ./a.out: error while loading shared libraries: libc.so.6: cannot create shared object descriptor: Cannot allocate memory
    (..)
    $ sh -c 'ulimit -d 27 ; ./a.out'
    ./a.out: error while loading shared libraries: libc.so.6: cannot create shared object descriptor: Cannot allocate memory
    $ sh -c 'ulimit -d 28 ; ./a.out'
    ./a.out: error while loading shared libraries: libc.so.6: cannot map zero-fill pages
    (...)
    $ sh -c 'ulimit -d 51 ; ./a.out'
    ./a.out: error while loading shared libraries: libc.so.6: cannot map zero-fill pages
    $ sh -c 'ulimit -d 52 ; ./a.out'
    str=(nil)
    (...)
    $ sh -c 'ulimit -d 175 ; ./a.out'
    str=(nil)
    $ sh -c 'ulimit -d 176 ; ./a.out'
    str=0x55b201c5a260