printf 从现象到本质

讲真,要深入理解 printf,只能自己看源码。666…


从现象到本质

前些时间,朋友问了一个问题:

printf%s 格式输出,如果参数是其它类型的数据强制转换为 char* 的,结果会怎么样?

我想最好的方法莫过于马上动手测试一下,看看结果。如果再问:printf 是线程安全的吗?… 问题很多,这些都只是问题的表象,要从现象看本质。Linux 是开源的,何不看源码理解程序工作原理呢?


从源码上看 strnlen 是通过查找内存的 ‘\0’ 字符串结束符的。如果强制转换的内存数据,没有 ‘\0’ 结束符,那 strnlen 就会出现问题。

/* https://github.com/torvalds/linux/blob/master/arch/x86/boot/printf.c */

int printf(const char *fmt, ...) {
    char printf_buf[1024];
    va_list args;
    int printed;

    va_start(args, fmt);
    printed = vsprintf(printf_buf, fmt, args);
    va_end(args);

    puts(printf_buf);

    return printed;
}

int vsprintf(char *buf, const char *fmt, va_list args) {
    ...
    switch (*fmt) {
        ...
        case 's':
            s = va_arg(args, char *);
            len = strnlen(s, precision);

            if (!(flags & LEFT))
                while (len < field_width--)
                    *str++ = ' ';
            for (i = 0; i < len; ++i)
                *str++ = *s++;
            while (len < field_width--)
                *str++ = ' ';
            continue;
    }
    ...
}

/* https://github.com/torvalds/linux/blob/master/arch/x86/boot/string.c */

size_t strnlen(const char *s, size_t maxlen) {
    const char *es = s;
    while (*es && maxlen) {
        es++;
        maxlen--;
    }

    return (es - s);
}

总结

不只 printf 的实现,很多基础函数,都能从 linux 源码中查看。可以从 github 下载一份源码,方便查看。下载个 zip 文件包吧,git 文件有点太大了。

/* https://github.com/torvalds/linux/blob/master/lib/string.c */

char *strcpy(char *dest, const char *src) {
    char *tmp = dest;

    while ((*dest++ = *src++) != '\0')
        /* nothing */;
    return tmp;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章