How do you know how much space to allocate with malloc()?

前端 未结 6 814
南旧
南旧 2021-02-14 06:31

I\'m a total C newbie, I come from C#. I\'ve been learning about memory management and the malloc() function. I\'ve also came across this code:

char         


        
6条回答
  •  时光说笑
    2021-02-14 07:11

    That snippet is allocating enough space for a 2-character name.

    Generally the string buffer is going to be filled from somewhere, i.e. I/O. If the size of the string isn't known ahead of time (e.g. reading from file or keyboard), one of three approaches are generally used:

    • Define a maximum size for any given string, allocate that size + 1 (for the null terminator), read at most that many characters, and error or blindly truncate if too many characters were supplied. Not terribly user friendly.

    • Reallocate in stages (preferably using geometric series, e.g. doubling, to avoid quadratic behaviour), and keep on reading until the end has been reached. Not terribly easy to code.

    • Allocate a fixed size and hope it won't be exceeded, and crash (or be owned) horribly when this assumption fails. Easy to code, easy to break. For example, see gets in the standard C library. (Never use this function.)

提交回复
热议问题