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

前端 未结 11 1742
难免孤独
难免孤独 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:40

    Once '\0' is added, does the memory just get returned, or is it sitting there hogging space until free() is called?

    There's nothing magical about \0. You have to call realloc if you want to "shrink" the allocated memory. Otherwise the memory will just sit there until you call free.

    If I stick a '\0' into the middle of the allocated memory, does (a.) free() still work properly

    Whatever you do in that memory free will always work properly if you pass it the exact same pointer returned by malloc. Of course if you write outside it all bets are off.

提交回复
热议问题