c++ - For-Loop on Pointer: Does it move the whole address range? -
i have bit of code:
int count_x(char* p, char x) { if (p == nullptr) return 0; int count = 0; (; *p != 0; p++) { if (*p == x) count++; } return count; } the input in case char-array:
char v[] = { "ich habe einen beispielsatz erstellt!"}; since looking cpp book "c++ programming language - 4th edition" got code there , trying figure out.
when stepping through it, noticed loop moves memory address in increments of one. not surprising me, following question arose , couldn't find answer yet: loop reduce overall memory range or whole range being moved?
since knowlege use "block" in whole storing such char-array (or type of array), guess later since don't see reducing boundries. "knowledge" have ask: doesn't cause major issues theoretically possible read parts of memory programm shouldn't have access to?
will have keep in mind when dealing (very) long arrays?
in c , c++, "strings this" implicitly nul-terminated. means end char value 0 or '\0' (same thing).
so loop:
for (; *p != 0; p++) advances p until reaches point *p 0 -- end of string.
if p not point within nul-terminated buffer or string, loop indeed move on memory beyond end of memory buffer started in. kind of error common , relying on strings being nul-terminated results (indirectly) in lot of buffer overruns, security holes, , crashing , memory corrupting programs.
to around this, c++ offers alternative ways store , interact strings of characters, including std::string. these not rely on positioned nul terminator work, although c-style code interact may.
and in c++17, string view provides non-owning low-cost way refer bounded size string no nul terminator.
Comments
Post a Comment