currently I am reading "A tour of C++" by Byarne Stroustrup. The thing that matters: on "pointers, arrays and references" he gave an example about using nullptr
like this:
int count_x(char* p, char x)
// count the number of occurrences of x in p[]
// p is assumed to point to a zero-terminated array of char (or to nothing)
{
if (p == nullptr) return 0;
int count = 0;
for (; p != nullptr; ++p)
if (*p == x)
++count;
return count;
}
In my my main:
int main(){
char* str = "Good morning!";
char c = 'o';
std::cout << count_x(str, c) << std::endl;
return 0;
}
When I run the program it crashes I get an exception thrown at line
if (*p == x)
If I change the loop to be like this:
for (; *p; p++)
if (*p == x)
++count;
Now everything works fine! I am using MSVC++ 14.0.
ideone
I don't get an exception but the result is always 0
which should be 3
:p != nullptr
and *p
perform very different checks.
The former checks that the pointer itself contains a non-null address. While the latter checks that the address being pointed at contains something that is not 0. One is clearly appropriate in the loop, where the buffer's content is checked, while the other is not.
You segfault because you never stop reading the buffer (a valid pointer is unlikely to produce null when it is incremented). So you end up accessing way beyond your buffer limit.