繁体   English   中英

为什么用 memcpy 和 sprintf 复制特定的缓冲区大小,在新缓冲区中打印的字符比原始缓冲区中的多?

[英]Why does copying a specific buffer size with memcpy and sprintf, prints more chars in new buffer than there are in the original buffer?

我有一个一般的理解问题! 这是我的代码:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <cstring>

int main() {
    // read user input
    char input[64] = {0};
    read(0, input, 64);
    printf("You've entered ");
    printf(input);

    char newbuf[128];
    char smallbuf[8];

    // copy into smallbuf 8 bytes of input
    memcpy(smallbuf, input, 8);

    // send smallbuf of 8 bytes as string into newbuf
    sprintf(newbuf, "%s", smallbuf);

    // print newbuf
    printf(&newbuf[0]);

    return 0;
}

我用 7 个字符得到的行为是可以的,它确实打印了 7 个字符:

$ gcc a.cpp -o a.out && ./a.out
1234567
You've entered 1234567
1234567
1234567

但是对于 8 个字符,它会打印出更多字符,我想知道为什么要这样做:

$ gcc a.cpp -o a.out && ./a.out 
12345678
You've entered 12345678
1234567812345678

谢谢你为我解释! :)

代码试图打印一个字符数组,就好像它是一个导致未定义行为字符串 smallbuf[]肯定不包含空字符,因此它不是字符串
"%s"需要一个指向字符串的匹配指针。

要么占空字符

char smallbuf[8+1];
memcpy(smallbuf, input, 8);
smallbuf[8] = '\0';
printf("%s", smallbuf);

或以精度限制输出。 打印最多 N 个字符或空字符的字符数组。

char smallbuf[8];
memcpy(smallbuf, input, 8);
printf("%.8s", smallbuf);

类似的问题适用于printf(input);


不要编码printf(input); 因为当input[]包含%时,这可能会导致未定义的行为

// printf(input);
printf("%s", input);

更好的代码会检查read(0, input, 64)的返回值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM