奇怪的错误:中止陷阱,同时处理字符数组用C [英] Weird Error: Abort trap while handling character array in C
问题描述
欲存储字符串中的每个字符的二进制值,并将其存储在数组中。但是,当我开始瞎搞像memset的功能,我有过调试无法控制。
I want to store the binary value of each character in the 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;
}
输出:
H => 01001000
E => 01100101
L => 01101100
L => 01101100
O => 01101111
中止陷阱
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 in the hand.
礼貌:这是一个老乡的修改程序栈的同胞用户@Athabaska
Courtesy: This is a modified program of a fellow stack fellow user @Athabaska.
谢谢!
推荐答案
海峡[8] ='\\ 0'
导致缓冲区溢出,因为 STR
只能有8个元素,而你试图访问第九之一。
str[8]='\0'
causes a buffer overflow because str
only has 8 elements, and you're trying to access the ninth one.
编辑:我抱怨'/ 0'
,但作为@R ..告诉我,它的是的有效的 - 但是, memset的()
最终将其参数转换为 unsigned char型
,所以我不认为有任何一点在使用它,所以我想笔者希望将其更改为'\\ 0'
。
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'
.
这篇关于奇怪的错误:中止陷阱,同时处理字符数组用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!