2

I want to allocate memory for a string using calloc, I know that calloc fills the whole allocated memory with 0, but I also found out that they are different from \0 in some contexts. This whole discussion it's kind of confusing for a newbie (like myself), so I was wondering if anyone could give me the final answer, if I use alloc to initialize a string do I have to manually set the last character to "\0" or not?

B.Castarunza
  • 135
  • 12
  • 4
    calloc zero initializes the allocated memory. and '\0' is zero.:) – Vlad from Moscow May 14 '20 at 21:45
  • 4
    The literal character `'\0'` is actually the octal escape for `0`. So the null terminator `'\0'` is really zero. – Some programmer dude May 14 '20 at 21:45
  • The major thing to remember when allocating memory for strings is to actually include the space for the terminator. – Some programmer dude May 14 '20 at 21:46
  • Thanks y'all for the quick answers! – B.Castarunza May 14 '20 at 21:49
  • There are a couple ways this can go wrong. 1) you allocate 5 bytes with `calloc` and then put a 5 character string into that memory (e.g. "hello"). That won't work, because "hello" needs 6 bytes, 5 for the letters and one more for the `'\0'` at the end. 2) you allocate 6 or more bytes, put "hello" into the memory, and then later attempt to change the string to "hi". That won't work unless there's a `'\0'` after the `i`. Without the `'\0'`, you get "hillo". – user3386109 May 14 '20 at 21:51
  • @user3386109 I see, it sure is a helpful reminder the second one, thanks – B.Castarunza May 15 '20 at 16:26

1 Answers1

3

There is no difference between integral value 0, with which calloc fills up the allocated memory, and literal character '\0', which is identical to integral value 0.

So if you write up to n-1 characters to a memory block of n characters allocated with calloc, you will always have a valid 0-terminated string.

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58