在 The C Programming Language 中练习3-5时,我遇到了以下意外行为。
#include <stdio.h>
#include <string.h>
// inspired by: http://www.eng.uerj.br/~fariasol/disciplinas/LABPROG/C_language/Kernighan_and_Ritchie/solved-exercises/solved-exercises.html/krx305.html
void reverse(char s[]) {
int c, i, j;
for ( i = 0, j = strlen(s)-1; i < j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
void itob(int n, char s[], int b) {
static char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int i = 0,
sign;
if ( b < 2 || b > 36 ) {
fprintf(stderr, "EX3_5: Cannot support base %d\n", b);
}
if ((sign = n) < 0) {
n = -n;
}
do {
s[i++] = digits[n % b];
} while (n /= b);
if (sign < 0) {
s[i++] = '-';
}
s[i] = '\0';
reverse(s);
}
int main() {
int base = 2,
input;
char buffer[5] = "0000";
input = 127;
itob(input, buffer, base);
printf("%d in base %d is %s\n", input, base, buffer);
// 127 in base 2 is 1111111
input = 128;
itob(input, buffer, base);
printf("%d in base %d is %s\n", input, base, buffer);
// 0 in base 2 is 10000000
// Why is input now 0?!
return 0;
}
为什么input
变量的值会发生变化(仅当input
大于127
时)?我是C的新手,但这似乎非常意外。据我所知,函数参数是按值传递的。
答案 0 :(得分:5)
你的缓冲区不够大。您为4个字符和一个空终止符分配了空格:
char buffer[5] = "0000";
但你正试图用itob(input, buffer, base);
填充8个字符和一个空终结符。这会导致缓冲区溢出和未定义的行为。
答案 1 :(得分:2)
尝试使用较大的buffer
尺寸,只有4个字符,您无法转换大于127的数字。