0

I want to store the binary value of each character in a string and store it in an array. But when i start messing around with functions like memset, i have no control over the debugging.

#include <stdio.h>
#include <string.h>
int main()
{
char str[8];
char *ptr = "Hello";
int i;

for(; *ptr != 0; ++ptr)
{
    printf("%c => ", *ptr);

    /* perform bitwise AND for every bit of the character */
    for(i = 7; i >= 0; --i) 
        if(*ptr & 1 << i) 
          str[7-i]='1';
        else
          str[7-i]='0';
        //(*ptr & 1 << i) ? putchar('1') : putchar('0');
    str[8]='\0';    
    printf("%s\n",str);
    memset(str,'/0',8);        
}
return 0;
}

Output:

H => 01001000
e => 01100101
l => 01101100
l => 01101100
o => 01101111
Abort trap

It would be nice if someone can throw some light. Even though i am getting the output, the trap is happening.

Courtesy: This is a modified program of a fellow stack fellow user @Athabaska.

3 Answers 3

3

str[8]='\0' causes a buffer overflow because str only has 8 elements, and you're trying to access the ninth one.

Edit: I complained about the '/0', but as @R.. informed me, it is valid - however, memset() will ultimately convert its parameter to unsigned char, so I don't think there is any point in using it, so I assume the author will want to change it to '\0'.

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

3 Comments

'/0' is valid C. It's a multi-character constant which has implementation-defined value, usually defined as interpreting the bytes in that order as a native-endian number.
@R..: +1; I didn't know that. Don't see the point of passing a multi-character value to a function that will ultimately convert its parameter to 'unsigned char', though...
Well on typical implementations, it would fill with either '/' or '0' depending on the system's endianness. :-)
3

str[8]='\0'; is invalid. If declaration is char str[8]; then valid indices are 0..7

Comments

2

str[] only has space for 8 characters, but you access the 9th: str[8] = '\0';

Comments

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.