Null-terminated strings (C++)

If you are working with strings you have two basic ways to define its length. Either you write a specific symbol at its end or you save/provide its length seperatly.


Null-terminated strings
All old school functions who operate with strings will do that on C-strings (char array) and nearly all of them will be null-terminated.

Not null-terminated strings
Many modern functions will operate on C++-Strings (std::string) instead, which contains of a not null-terminated string and its length.


Showcase: printf with not null-terminated strings

#include <stdio.h>
#include <memory.h>

int main()
{
    char buf1[3];
    memcpy(buf1, "aaa", sizeof(buf1));
    char buf2[3];
    memcpy(buf2, "bbb", sizeof(buf2));
    char buf3[3];
    memcpy(buf3, "ccc", sizeof(buf3));

    // it will write to stdout till it reaches a '\0' (0x00)
    printf("%s\n", buf1);

    // but it can also work with not null-terminated strings
    printf("%.*s\n", static_cast<int>(sizeof(buf1)), buf1);

    return 0;
}
$ g++ main.cpp -g
$ gdb a.out
(gdb) b 18
(gdb) r
aaabbbccc
aaa
(gdb) x/10x &buf1
0x7fffffffdcbf:	0x61	0x61	0x61	0x62	0x62	0x62	0x63	0x63
0x7fffffffdcc7:	0x63	0x00