Why strlen() is giving wrong value for a char array with undefined array size?

120 Views Asked by At
#include<stdio.h>
#include<string.h>
int main(){
  int a[]={1,2,3,4};
  int size= sizeof(a)/sizeof(int);
  printf("\nSize/capacity of integer type array(with no limit) %d\n",size);

  int a1[6]={1,2,3,4};
  int size1= sizeof(a1)/sizeof(int);
  printf("\nSize/capacity of integer type array(with a limit of 7) %d\n",size1);

printf("\n");

  char b[7]={'a','b','c','d','e'};
  int size2= sizeof(b)/sizeof(char);
  int length=strlen(b);
  printf("\nSize/capacity of char type array(with a limit of 7) %d\n",size2);
  printf("\nNumber of char type data in the array %d\n",length);

  char br[]={'k','l'};
  int size3= sizeof(br)/sizeof(char);
  int length1=strlen(br);
  printf("\nSize/capacity of char type array(with no limit) %d\n",size3);
  printf("\nNumber of char type data in the array length1 %d\n",length1);    //answer should have been 2

 return 0;
}`

It gave me 7 as an output for the value length1. When I commented out the upper block(above the initialization of br[]) the array length came out as 3. I want to know why this is happening and the solution. I am new to this but thanks in advance.

The output for the code above:

Size/capacity of integer type array(with no limit) 4

Size/capacity of integer type array(with a limit of 7) 6

Size/capacity of char type array(with a limit of 7) 7

Number of char type data in the array 5

Size/capacity of char type array(with no limit) 2

Number of char type data in the array length1 7

3

There are 3 best solutions below

3
George On BEST ANSWER

strlen works by looking for the null terminator '\0', and your character arrays don't end with a null terminator character.

Change this

char br[]={'k','l'};

to this

char br[]={'k','l', '\0'};

and make a similar change to b (plus adding 1 to the size of the array) and see what happens.

0
dbush On

strlen doesn't tell you the length of a character array, it tells you the length of a null-terminated string. The array br does not hold a string because it's only long enough to hold the individual characters that were used to initialize it, and those don't include a byte with value 0.

If you used a string literal to initialize the array instead of an initializer list of characters:

char br[]="kl";

Then the array would be sized to include the terminating null byte that's part of the string literal, and you can then use string functions on it.

1
Masklinn On
$ man strlen:
[...]
The strlen() function computes the length of the string s
[...]
$ man string:
[...]
The string functions manipulate strings that are terminated by a null byte.
[...]

"A char array" which ends in 4, 'e', or 'l' is not null-terminated, therefore not a string, therefore calling strlen on one is UB.