It is because strlen
works with "C-style" null terminated strings. If you give it a plain pointer or uninitialised buffer as you did in your first example, it will keep marching through memory until it a) finds a
, at which point it will return the length of that "string", or b) until it reaches a protected memory location and generates an error.
Given that you've tagged this C++, perhaps you should consider using std::array
or better yet, std::string
. Both provide length-returning functions (size()
) and both have some additional range checking logic that will help prevent your code from wandering into uninitialised memory regions as you're doing here.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…