Weird Error: Abort trap while handling character array in C

杀马特。学长 韩版系。学妹 提交于 2019-12-12 05:24:43

问题


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.


回答1:


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




回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/5680367/weird-error-abort-trap-while-handling-character-array-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!