Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replacing decayed array with a pointer to array resulting in segmentation fault

I was trying to loop through an array using pointers:

#include <iostream>
#include <iterator>

int main() 
{
    char name[]{ "Abhi" };

    for (char* ptr_c{ name }; ptr_c != (ptr_c + std::size(name)); ++ptr_c) {
        std::cout << *ptr_c;
    } 

    std::cout << "\n";
}

This results in: Error: Segmentation fault core dumped

However, in the for loop’s condition testing:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 for (char* ptr_c{ name }; ptr_c != (ptr_c + std::size(name)); ++ptr_c)
                                     ^^^^^^  

Replcaing ptr_c with name makes it work. Why?
Shouldn’t name decay to ptr_c anyway?

>Solution :

ptr_c != ptr_c + std::size(name)

This condition is never false. If you add a non-zero number to a pointer, the resulting pointer will never equal the original pointer. Hence, the infinite loop overflows the array.

Shouldn’t name decay to ptr_c anyway?

No. name always decays to a pointer to the first element. ptr_c only starts as the first element, but after the first iteration, it points to other elements.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading