What are the problems of a zero-terminated string that length-prefixed strings overcome?

后端 未结 6 1768
滥情空心
滥情空心 2021-02-06 21:57

What are the problems of a zero-terminated string that length-prefixed strings overcome?

I was reading the book Write Great Code vol. 1 and I had that question in mind.<

6条回答
  •  野性不改
    2021-02-06 22:43

    First a clarification: C++ strings (i.e. std::string) aren't weren't required to end with zero until C++11. They always provided access to a zero-terminated C string though.

    C-style strings end with a 0 character for historical reasons.

    The problems you're referring to are mainly bound to security issues: zero ended strings need to have a zero terminator. If they lack it (for whatever reason), the string's length becomes unreliable and they can lead to buffer overrun problems (which a malicious attacker can exploit by writing arbitrary data in places where it shouldn't be.. DEP helps in mitigating these issues but it's off-topic here).

提交回复
热议问题