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

Weird bug in pointers

I was trying to access single bytes of an int value via the code below. My problem is that whenever I try to remove long int i=0; from the code, it gives me a segmentation fault. Is there any reason this happens? I am not using I anywhere in the code.

// Online C++ compiler to run C++ program online
#include <iostream>

int main() {
    // Write C++ code here
    
    unsigned int* a; 
    
    unsigned char* b1;
    unsigned char* b2; 
    unsigned char* b3; 
    unsigned char* b4;
    
    *a= 4294967295; //set to max val (4 bytes)
    //*************************
    long int i=0;//Q. Why long int/long long int? 
    //*************************
    
    b1 = (unsigned char*)(a);
    b2 = b1+(long long int)1;
    b3 = b1+(long long int)2;
    b4 = b1+(long long int)3;
    
    std::cout <<*a<<" "<<(int)*b1<<" "<<(int)*b2<<" "<<(int)*b3<<" "<<(int)*b4<<std::endl;
    
    
    return 0;
}

>Solution :

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

This exhibits undefined behavior:

unsigned int* a; 
*a= 4294967295; //set to max val (4 bytes)

The pointer variable a is never initialized to anything, so it points to a random memory address. Writing anything to that random garbage address (typically) causes a segmentation fault. It’s just coincidence that adding another variable changes the behavior (due to a change in memory layout of the program).

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