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

前端 未结 6 831
南旧
南旧 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条回答
  •  -上瘾入骨i
    2021-02-14 07:00

    This will allocate three bytes; 1 for sizeof(char), plus two. Just seeing that line out of context, I have no way of knowing why it would be allocated that way or if it is correct (it looks fishy to me).

    You need to allocate enough memory to hold whatever you need to put in it. For example, if you're allocating memory to hold a string, you need to allocate enough memory to hold the longest string expected plus one byte for the terminating null. If you're dealing with ASCII strings, that's easy: one byte per character plus one. If you're using unicode strings, things get more complicated.

提交回复
热议问题