Is using strlen() in the loop condition slower than just checking for the null character?

前端 未结 8 784
鱼传尺愫
鱼传尺愫 2020-12-07 00:39

I have read that use of strlen is more expensive than such testing like this:

We have a string x 100 characters long.

I think that<

8条回答
  •  隐瞒了意图╮
    2020-12-07 01:08

    It's worth noting that you may be opening yourself up to buffer overflow problems if you don't also test the index against the size of the buffer containing the string. Depending on what you're doing with this code, this may or may not be a practical issue, but it rarely hurts to have extra checks, and it's a good habit to get into.

    I'd suggest: for (i = 0; i < buf_size && x[i] != '\0'; i++)

    Where:

    • buf_size is the predetermined size of the buffer. If x is an array, this will be sizeof(x); if x is a pointer, you should have the buffer size available.
    • I've removed the declaration of i from the loop because it's only valid c99. If you're only compiling under c99, feel free to put it back in.

提交回复
热议问题