Example in 5.6 -- undefined behavior if I increment a pointer without any validation? [Answer: Segmentation Fault]

In the example in section 5.6

char ** table_of_sentences;
char * frase1;
char * frase2;

table_of_sentences = &frase1;
table_of_sentences ++;
table_of_sentences = &frase2;

What is the purpose of the line table_of_sentences ++; ?
Couldn’t it cause undefined behavior if table_of_sentences = &frase2; wasn’t coming right after it ?

Hi @versavel,

Good question.

The purpose of table_of_sentences ++ is to increment the pointer-to-pointer, exactly as you thought.

Now, about the next question:

Couldn’t it cause undefined behavior if table_of_sentences = &frase2; wasn’t coming right after it ?

You are right here. When working with pointers you have to be careful, because when you increment it, it is going to point to the next address. If the address is used by a variable of another type, and you try to access it, it is going to show you invalid data, or your program is going to crash with “segmentation fault”.

Whenever you see a Segmentation Fault, be sure you have a pointer’s problem.

Let’s see the code below:


#include <iostream>
using namespace std;

int  main() {

    char name1[] = "Versatile";
    char name2[] = "Vel";
    int year = 2023;

    char *name1_pointer = name1;
    char *name2_pointer = name2;

    char **table_of_letters;

    table_of_letters = &name1_pointer;
    cout<<table_of_letters<<" = " << (*table_of_letters) <<endl;

    table_of_letters++;
    cout<<table_of_letters<<" = " << (*table_of_letters) <<endl;

    table_of_letters++;
    cout<<table_of_letters<<" = " << (*table_of_letters) <<endl;

    return 0;
}

If I compile, it:

g++ main.cpp -o versatile

When I run it with ./versatile, this is what I have:

0x7ffe487d19e0 = Versatile
0x7ffe487d19e8 = Vel
0x7ffe487d19f0 = �}H�

I could well have a Segmentation Fault.

Again, you have to be careful when working with pointers.

#KeepPushingYourROSLearning

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.