What happens to memory after '\0' in a C string?

前端 未结 11 1555
难免孤独
难免孤独 2020-12-23 11:25

Surprisingly simple/stupid/basic question, but I have no idea: Suppose I want to return the user of my function a C-string, whose length I do not know at the beginning of th

11条回答
  •  醉梦人生
    2020-12-23 11:43

    \0 is just one more character from malloc and free perspective, they don't care what data you put in the memory. So free will still work whether you add \0 in the middle or don't add \0 at all. The extra space allocated will still be there, it won't be returned back to the process as soon as you add \0 to the memory. I personally would prefer to allocate only the required amount of memory instead of allocating at some upper bound as that will just wasting the resource.

提交回复
热议问题