cstringoff-by-one

Weird Error: Abort trap while handling character array in C


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.


Solution

  • 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'.