samedi 13 janvier 2024

Segmentation fault on nullptr check when incrementing the ptr to iterate over an array

The following code, when compiled and run gives a segmentation fault. I was trying out the sample on page 12 of a Tour of C++ on a MacBook.

compilation command - clang++ -Wall -std=c++11 -o replacement.o replacement.cpp && ./replacement.o

Error message - 'zsh: segmentation fault ./replacement.o'

Full code -

#include <iostream>

int count_occurances(char* p, char x)
{
    int count = 0;
    // count number of times x occurs in p
    while (p != nullptr)
    {
        if (*p == x)
            ++count;
        ++p;
    }
    return count;
}

int main(int argc, const char * argv[]) {
    // insert code here...
    char num_array[4] = {'a', 'b', 'b', 'c'};
    std::cout << "Running count occurances array" << count_occurances(num_array, 'b') << "done\n" ;
    return 0;
}

Essentially tried to iterate over the array by incrementing the pointer but somehow messing up the nullptr check, as a result it's accessing memory it shouldn't.

Aucun commentaire:

Enregistrer un commentaire