Search code examples
cstringstrlen

Why is strlen working fine without '\0'?


As title, I have some question using char* in c. For example, if I write this

char *a = calloc(5, 5);
a[0] = '1';
a[1] = '1';
a[2] = '1';
a[3] = '1';
a[4] = '1';
printf("a = %s, length = %d", a, strlen(a));

and the output is

a = 11111, length = 5

Why is strlen working fine without '\0'? Can someone help me understand?


Solution

  • calloc(5, 5) allocates and zeroes 25 bytes. You assign the first five of these, but the sixth is still '\0'.