Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ dangerous pointers practice? [duplicate]

Tags:

c++

pointers

#include <stdio.h>


int *pPointer;

void SomeFunction()
{
    int nNumber;
    nNumber = 25;    

    // make pPointer point to nNumber:

    pPointer = &nNumber;
}

void main()
{
    SomeFunction(); // make pPointer point to something

    cout<< "Value of *pPointer: "<< *pPointer <<endl;
}

I have been told that using pointers like this is dangerous, could anyone please explain why it is dangerous and what would be the 'safe' way to write that piece of code? will 25 always be printed out to the screen in that way? if not then why?

like image 907
yair Avatar asked Mar 20 '26 02:03

yair


1 Answers

Using a pointer to local variable outside of the scope of the variable is always dangerous. It invokes undefined behavior.

like image 109
Ivaylo Strandjev Avatar answered Mar 21 '26 14:03

Ivaylo Strandjev