c - 为什么在C程序中变量被突变?

标签 c kernighan-and-ritchie

在通过C编程语言进行练习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语言的新手,但这似乎非常令人意外。据我了解,函数参数是按值传递的。

最佳答案

您的缓冲区不够大。您为4个字符和一个空终止符分配了空间:

char buffer[5] = "0000";


但您尝试使用itob(input, buffer, base);在其中填充8个字符和一个空终止符。这导致缓冲区溢出和未定义的行为。

关于c - 为什么在C程序中变量被突变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42358716/

相关文章:

c - getop() 函数 K&R 书第 78 页

c - C 中的 if(Expr,Expr) 结构?

c - 我可以从 pic 18f4550 的 PORTBbits.RB7 看哪个值

c - 具有 `fcn( char *, ...)` 的可变参数函数如何知道何时结束?

c - 十六进制到十进制的转换 [K&R 练习]

c - getword 中的段错误

c - 为什么 C 库链接顺序只在某些系统上很重要?

c - 检测笔式驱动器

c - 数组与常量指针一样还是有其他区别?

c - K&R 1.6 Arrays//数组构造中的数字表示