-3

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?

CinCout
  • 9,486
  • 12
  • 49
  • 67
Tony Lin
  • 765
  • 3
  • 15
  • 35

1 Answers1

3

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

aschepler
  • 70,891
  • 9
  • 107
  • 161
  • Sorry, I typed wrong. It's calloc(5,sizeof(char)) – Tony Lin Apr 26 '17 at 04:44
  • @tonylin if it's `calloc(5,sizeof(char))` then you get undefined behaviour. `calloc(5,sizeof(char))` allocated 5 bytes. It seems to work in your case because the byte immediately following the 5 allocated bytes is 0 by chance, but actually it's value is indetermined, so if you run your program on another computer or if you compile it with another compiler or maybe if you just reboot your computer it may very well not work any more. – Jabberwocky Apr 26 '17 at 07:56