Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null byte stops for `print` but not `strlen`, why?

Tags:

string

dart

nul

I was playing around with Dart strings and noticed this:

print("\x00nullbyte".length);
print("\x00nullbyte");

If you run this, you'll find that the length is 9, which includes the null byte. But there is no output.

Trusting Google engineers more than myself, programming-wise, I'm thinking there might be a reason for that. What could it be?

like image 903
conradkleinespel Avatar asked Feb 12 '14 04:02

conradkleinespel


1 Answers

The Dart string has length 9, and contains all nine code units. NUL characters are perfectly valid in a Dart string. They are not valid in C strings though, where they mark the end of the string. When printing, the string is eventually converted to a C-string to call the system library's output function. At that point, the system library sees only the NUL character and prints nothing.

Try:

main() { print("ab\x00cd"); }  // prints "ab".

The String.length function works entirely on the Dart String object, and doesn't go through the C strlen function. It's unaffected by the limits of C.

Arguably, the Dart print functionality should detect NUL characters and print the rest of the string anyway.

like image 120
lrn Avatar answered Sep 23 '22 17:09

lrn