Home > Enterprise >  Weird bug in pointers
Weird bug in pointers

Time:05-06

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;
}

CodePudding user response:

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).

CodePudding user response:

The posted program has Undefined Behavior(1):

unsigned int* a;  // Uninitialized local variable, it has an indeterminated value. 
*a = 4294967295;  // Where is it assigned?

It's unfortunate that it happens to "work" in your environment, you should enable more warnings.

Since C 20, you can use std::bit_cast to reinterpret an object representation:

#include <array>
#include <bit>
#include <iostream>

int main()
{
  auto a{ 4294967295LL };
  using repr_t = std::array<std::byte, sizeof(a)>;
  
  auto b{ std::bit_cast<repr_t>(a) };
  
  // The following outputs:      4294967295   255 255 255 255 0 0 0 0
  std::cout << a << "  ";
  for (auto i : b)
    std::cout << ' ' << static_cast<int>(i);
  std::cout << '\n';    
}

(1) See e.g.:

Undefined, unspecified and implementation-defined behavior

Where exactly does C standard say dereferencing an uninitialized pointer is undefined behavior?

  • Related