There is code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *str = calloc(3, sizeof(char));
str[2] = '\0';
printf("%ld", strlen(str));
free(str);
}
Expected output 2
Actual output 0
Why?
As far as I understood strlen counts symbols before \0. Maybe str[0] and str[1] are already ‘\0’?
>Solution :
calloc() initializes allocated memory with all \0. You then set the last byte to \0 – it’s already that value from initialization.
strlen() counts the chars before the first \0. Since the very first char is already \0, the length is zero.