Weird Error: Abort trap while handling character a

2019-09-15 09:58发布

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条回答
兄弟一词,经得起流年.
2楼-- · 2019-09-15 10:06

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

查看更多
戒情不戒烟
3楼-- · 2019-09-15 10:19

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

查看更多
别忘想泡老子
4楼-- · 2019-09-15 10:23

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

查看更多
登录 后发表回答