0

This is what I've tried, my logic is that my tmp shifting left 31 times will get compared to the user input integer I and a value of 1 or 0 will be inserted to index str[0] -> str[31] and the I null terminate str[32] with the \0.

However, I'm getting a segmentation fault.

P.S. I'm not allowed to change the parameters of this function and my professor set the size of str to be 33 in the main, which, I'm not allow to change either.

void int2bitstr(int I, char *str) {
        int tmp = 1 << 31;
        do{
                *str++ = !!(tmp & I) + '0';
        } while(tmp >>= 1);
        *str = '\0';
}
4
  • 3
    int is signed. Have you forgotten about it? Commented Sep 20, 2017 at 16:01
  • I always use Valgrind to understand segfaults Commented Sep 20, 2017 at 16:05
  • 1
    Building on what Eugene said, I think you would be surprised at your output if you print the value of tmp to your console with each iteration, especially in consideration of your loop-exit clause. Commented Sep 20, 2017 at 16:16
  • @HansPetterTaugbølKragset I got the program to work, I'm actually new to c and never heard of valgrind; thankyou for your suggestion, I'll keep it in mind! Commented Sep 20, 2017 at 18:58

1 Answer 1

1

Try making tmp an unsigned int. The behaviour of right-shifting a negative (signed) integer is implementation-defined, and in your case is likely shifting in 1s (the original MSB) thus causing the loop to exceed the length of str.

Sign up to request clarification or add additional context in comments.

2 Comments

int tmp = 1 << 31; --> unsigned tmp = 1u << 31; (be sure to change to 1u)
Thank you! The program works fine now, I can't believe I forget about this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.