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

前端 未结 6 826
南旧
南旧 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 06:57

    Well, for a start, sizeof(char) is always 1, so you could just malloc(3).

    What you're allocating there is enough space for three characters. But keep in mind you need one for a null terminator for C strings.

    What you tend to find is things like:

    #define NAME_SZ 30
    : : :
    char *name = malloc (NAME_SZ+1);
    

    to get enough storage for a name and terminator character (keeping in mind that the string "xyzzy" is stored in memory as:

    +---+---+---+---+---+----+
    | x | y | z | z | y | \0 |
    +---+---+---+---+---+----+
    

    Sometimes with non-char based arrays, you'll see:

    int *intArray = malloc (sizeof (int) * 22);
    

    which will allocate enough space for 22 integers.

提交回复
热议问题