Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why NULL terminated string's length is smaller than expected in C?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading