4

I am trying to use implement the LSB lookup method suggested by Andrew Grant in an answer to this question: Position of least significant bit that is set

However, it's resulting in a segmentation fault. Here is a small program demonstrating the problem:

#include <iostream>

typedef unsigned char Byte;

int main()  
{  
    int value = 300;  
    Byte* byteArray = (Byte*)value;  
    if (byteArray[0] > 0)  
    {  
        std::cout<< "This line is never reached. Trying to access the array index results in a seg-fault." << std::endl;  
    }  
    return 0;  
}  

What am I doing wrong?
I've read that it's not good practice to use 'C-Style' casts in C++. Should I use reinterpret_cast<Byte*>(value) instead? This still results in a segmentation fault, though.

Community
  • 1
  • 1
peace_within_reach
  • 237
  • 2
  • 4
  • 14

5 Answers5

13

Use this:

(Byte*) &value;

You don't want a pointer to address 300, you want a pointer to where 300 is stored. So, you use the address-of operator & to get the address of value.

Erik
  • 88,732
  • 13
  • 198
  • 189
9

While Erik answered your overall question, as a followup I would say emphatically -- yes, reinterpret_cast should be used rather than a C-style cast.

Byte* byteArray = reinterpret_cast<Byte*>(&value);
ildjarn
  • 62,044
  • 9
  • 127
  • 211
1

The line should be: Byte* byteArray = (Byte*)&value;

You should not have to put the (void *) in front of it.

-Chert

0
char *array=(char*)(void*)&value;

Basically you take a pointer to the beginning of the string and recast it to a pointer to a byte.

Blindy
  • 65,249
  • 10
  • 91
  • 131
0

@Erik already fixed your primary problem, but there is a subtle one that you still have. If you are only looking for the least significant bit, there is no need to bother with the cast at all.

int main()
{
    int value = 300;       
    if (value & 0x00000001)       
    {           
        std::cout<< "LSB is set" << std::endl;
    }
    return 0;
}
Zac Howland
  • 15,777
  • 1
  • 26
  • 42
  • He's looking for *position* of the least significant *set* bit. Which, obviously, can still be found without any byte array. – Erik Mar 09 '11 at 19:15
  • In that case, his implementation is entirely wrong. What he has now will only check to see if the lowest byte is equal to 1. – Zac Howland Mar 09 '11 at 19:17
  • Yep, but as he states, the code is a demo of a specific problem. My answer addresses that specific problem. If it's his real code, then it needs some work :P – Erik Mar 09 '11 at 19:23
  • Yes -- Sorry for the confusion. The code I posted is just a demonstration of the crash. The actual code is using a byte array in a similar way, but with a lot of other things going on. – peace_within_reach Mar 09 '11 at 19:26
  • No problem, but in either case, there is no need for a cast to to a byte to find the least significant set bit in an integer. In fact, doing the cast would actually make it more complicated. – Zac Howland Mar 09 '11 at 19:31