Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

length of string containing \0

Tags:

c++

c

 char p[]="abc\012\0x34"; 
 printf("%d\n",strlen(p));

I am getting output 4. Shouldn't it be 3 ??? Although for following i am getting 3.

 char p[]="abc\0"; 
 printf("%d\n",strlen(p));
like image 669
is0dvil Avatar asked Nov 30 '22 16:11

is0dvil


2 Answers

Your string does contain four characters before the \0, i.e. abc and \012.

The latter is a valid octal escape sequence, which is 10 in decimal, i.e an ASCII linefeed character.

\0x34 on the other hand isn't valid octal - only the \0 part is valid hence that's the real end of your NUL terminated string.

like image 165
Alnitak Avatar answered Dec 15 '22 04:12

Alnitak


\012 is an octal escaped character, not a NUL followed by 1 and 2. x terminates the second octal character so it is genuinely a NUL. (\x34 would be the correct form for a hexadecimal escaped character.)

The representation of a NUL character as \0 is just a special case of an octal escape sequence. In general a \ can be followed by one, two or three octal digits to form a valid octal escape sequence in a character or string literal.

like image 41
CB Bailey Avatar answered Dec 15 '22 04:12

CB Bailey