samedi 7 mars 2020

Use an integer (int) as a pointer argument

If we ignore the aspects:

  1. Bad practice
  2. Unjustified need
  3. and probably others ...

What are the risks (run-time : crash, undefined behavior, segmentation fault. implementation-defined behavior : wrong address generation) of this program as long as the address remains in the interval INT_MIN and INT_MAX:

#include <iostream>
using namespace std;
#include <sstream> 
#include <string>  

#define TAB_SIZE 2

void UseIntAsAdress (unsigned int  i)
{
    int *pTab =  (int*) i;
    for (int i=0; i< TAB_SIZE; i++)
        cout << "tab ["<<i<<"] = "<< pTab[i] <<endl;
}

int main()
{
    int *pTab = new int [TAB_SIZE];
    for ( int i=0; i<TAB_SIZE; i++)
        pTab [i] = i; 

    std::stringstream streamAdr;
    streamAdr << pTab;  
    std::string name = streamAdr.str(); 

    unsigned int i = stoi(name.c_str(), 0, 16);

    UseIntAsAdress (i);

    delete [] pTab;
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire