Kevin Hummerwood
Kevin Hummerwood

Reputation: 79

segmentation fault while trying to manipulate bits

I am studying through a book called Computer Systems: A Programmer's Perspective to gain some insight about the inner workings of modern computers.

Tonight I was trying to look inside int's and unsigned's to see of what bits they are made. I came up with this:

#include <stdbool.h>
#include <stdio.h>
typedef unsigned char * byte_pointer;
void bp2b(byte_pointer bp, bool bits[8]){
   unsigned char n;
   for (n = 0; n<8; n++){
      if (*bp & (1 << n))
         bits[7-n] = true;
      else bits[7-n] = false;
   }
}
void show_byte(byte_pointer bp){
   int ind;
   bool bits[8];
   bp2b(bp, bits);
   for (ind = 0; ind < 8; ind++){
      printf("%d",bits[ind]);
   }
   printf("\n");
}

int main(void){
   int x;
   x = 1;
   show_byte((byte_pointer) x);
}

Why did I get a segfault? My knowledge of C is fairly limited, so don't hesitate to point out mistakes that seem obvious to you.

EDIT: forgot the main function.

Upvotes: 0

Views: 805

Answers (1)

jpw
jpw

Reputation: 44901

You're casting a non-pointer value to a pointer: (byte_pointer) x and then dereferencing it, this won't work. Try to take the address of x and cast that: (byte_pointer) &x instead.

Make this change and your program will run, but be aware that casting an int to an unsigned char might lead to loss of information as the unsigned char is a narrower type than the int (in most implementations).

Setting x = 255 will yield 11111111 while setting x = 256 will yield 00000000.

Upvotes: 2

Related Questions