为什么分段错误+我怎样才能摆脱它?
Why the segmentation fault + how can I get rid of it?
我输入了这些代码 + 我遇到了分段错误。我正在尝试制作我自己的特殊版本 strtol
:
struct optional_int {int Value; char IsNull;};
struct optional_int StrToHex(char Str[]) {
const char Hex[0x10] = "0123456789ABCDEF";
unsigned int Chr = 0x00,i,j,Number = 0x00;
unsigned char IsNull, IsNegative;
if(Str[0x0] == '-') {
IsNegative = 0x1;
int N_C_Char = 0;
while( Str[N_C_Char] != '[=10=]' ) {
Str[N_C_Char]=Str[N_C_Char+1];//right here
N_C_Char++;
}
}else{IsNegative=0;}
printf("%sfas", Str);
for(i = strlen(Str); i > 0; i--){
unsigned int Successes = 0x0;
for( j = 0; j < 0x10; j++ ) {
if( Str[Chr]==Hex[Chr]) {
Number+=((pow(0x10, i))*j);
Successes++;
}
}
if(Successes!=1) {
IsNull = 1;
}else{
IsNull = 0;
Number = 0;
}
Chr++;
}
if(IsNegative == 1) {
return (struct optional_int){ Number, IsNull};
}else{
return (struct optional_int){-Number, IsNull};
}
}
int main(int argc, const char *argv[]) {
printf("asdf %x\n", StrToHex("-535").Value);
}
每当我给它一些负数时,它都会给我一个分段错误核心转储,但我已经找到了问题所在。
好的,所以我明白了。问题确实是您传递给函数的字符串。当你写 "-535"
时,字符串被分配在程序的数据部分,你不能写它。当数字为负数时,您尝试通过将数字移动到 -
符号上来修改该字符串。这就是它仅在负数时崩溃的原因。
int main(int argc, const char *argv[]) {
char c[200];
strcpy(c, "-535");
printf("asdf %x\n", StrToHex(c).Value);
}
此代码段适用于 main
函数。您将永远无法将常量字符串传递给引用此类字符串的函数或指针:
char c[200] = "-535";
StrToHex(c);
也会崩溃。
您必须提供您具有写入权限的内存位置。
您的问题的另一个解决方法是不更改字符串以删除 -
,而是编写您的代码以忽略它:)
我输入了这些代码 + 我遇到了分段错误。我正在尝试制作我自己的特殊版本 strtol
:
struct optional_int {int Value; char IsNull;};
struct optional_int StrToHex(char Str[]) {
const char Hex[0x10] = "0123456789ABCDEF";
unsigned int Chr = 0x00,i,j,Number = 0x00;
unsigned char IsNull, IsNegative;
if(Str[0x0] == '-') {
IsNegative = 0x1;
int N_C_Char = 0;
while( Str[N_C_Char] != '[=10=]' ) {
Str[N_C_Char]=Str[N_C_Char+1];//right here
N_C_Char++;
}
}else{IsNegative=0;}
printf("%sfas", Str);
for(i = strlen(Str); i > 0; i--){
unsigned int Successes = 0x0;
for( j = 0; j < 0x10; j++ ) {
if( Str[Chr]==Hex[Chr]) {
Number+=((pow(0x10, i))*j);
Successes++;
}
}
if(Successes!=1) {
IsNull = 1;
}else{
IsNull = 0;
Number = 0;
}
Chr++;
}
if(IsNegative == 1) {
return (struct optional_int){ Number, IsNull};
}else{
return (struct optional_int){-Number, IsNull};
}
}
int main(int argc, const char *argv[]) {
printf("asdf %x\n", StrToHex("-535").Value);
}
每当我给它一些负数时,它都会给我一个分段错误核心转储,但我已经找到了问题所在。
好的,所以我明白了。问题确实是您传递给函数的字符串。当你写 "-535"
时,字符串被分配在程序的数据部分,你不能写它。当数字为负数时,您尝试通过将数字移动到 -
符号上来修改该字符串。这就是它仅在负数时崩溃的原因。
int main(int argc, const char *argv[]) {
char c[200];
strcpy(c, "-535");
printf("asdf %x\n", StrToHex(c).Value);
}
此代码段适用于 main
函数。您将永远无法将常量字符串传递给引用此类字符串的函数或指针:
char c[200] = "-535";
StrToHex(c);
也会崩溃。
您必须提供您具有写入权限的内存位置。
您的问题的另一个解决方法是不更改字符串以删除 -
,而是编写您的代码以忽略它:)