Saturday, April 19, 2025

C++ Null Pointer

To realize why NULL Pointers are useful, furst run this code to print junk value at memory location.

Junk value means we are dealing with values that are leftovers from previous operations: 

#include <iostream>

using namespace std;

int main() {

    int *somePointer;

    cout << "Address: " << somePointer << endl;

    cout << "Garbage Value: " << *somePointer << endl;

    return 0;

}

Result:

Address: 0x4270ce
Garbage Value: 1528349827

Process returned 0 (0x0)   execution time : 0.021 s
Press any key to continue.

Bottom line, we never intentionally pushed 1528349827 at memory location 0x4270ce. 

Let's play with a pointer pointing to values of different data types:

#include <iostream>

using namespace std;

int main() {

    int *somePointer;
    float *anotherOne;
    double *someMore;

    cout << "Address: " << somePointer << endl;
    cout << "Address: " << anotherOne << endl;
    cout << "Address: " << someMore << endl;

    cout << "Garbage Value: " << *somePointer << endl;
    cout << "Garbage Value: " << *anotherOne << endl;
    cout << "Garbage Value: " << *someMore << endl;

    return 0;

}

Result:

Address: 0x4271be
Address: 0x6dff80
Address: 0x427160
Garbage Value: 1528349827
Garbage Value: 1.01019e-038
Garbage Value: -1.39062e-284

Process returned 0 (0x0)   execution time : 0.064 s
Press any key to continue.

And now we will use NULL Pointer to evade possibility of using junk values: 

#include <iostream>

using namespace std;

int main() {

    int *somePointer = NULL;
    float *anotherOne = NULL;
    double *someMore = NULL;

    cout << "Address: " << somePointer << endl;
    cout << "Address: " << anotherOne << endl;
    cout << "Address: " << someMore << endl;

    cout << "Garbage Value: " << *somePointer << endl;
    cout << "Garbage Value: " << *anotherOne << endl;
    cout << "Garbage Value: " << *someMore << endl;

    return 0;

}

Result:

Address: 0
Address: 0
Address: 0

Process returned -1073741819 (0xC0000005)   execution time : 0.675 s
Press any key to continue.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...