关于为什么字符串在\ 0的第一个实例上被截断的问题

2 c++ pointers

我有一个函数,通过串口一次读取一个字符,一个字节.收集这些字节后,它们将传递给处理字节和消息的方法.

我知道如何解决问题(修复方法如下),但为什么在不执行修复时我的字节会被截断?

unsigned char dpBuf[255];
...

// Pretend dpBuf has values 0x01 0x02 0x03 0x00 0x00 0x00 0x04 0x05
..
ProcessMsg(dpBuf);
..
void ProcessMsg(unsigned char *buff)
{
    // buff comes in as 0x01 0x02 0x03 0x00 and rest is truncated
    char p[255];
    ...
    for (int i = 0; i < sizeof(buff); i++) 
    {
        sprintf(p, " 0x%X ", (unsigned char)b[i]);
    }
    ..
}
Run Code Online (Sandbox Code Playgroud)

固定:

ProcessMsg((unsigned char*)&dpBuf, length); // instead of sizeof() in the loop, use length

..

void ProcessMsg (unsigned char *buff, int length)
{
    // buff comes in as the original character string and is not truncated
    .. 
    // do for loop, print out contents

}
Run Code Online (Sandbox Code Playgroud)

sth*_*sth 11

buff声明为const char*,所以sizeof(buff)返回这样一个指针的大小,这似乎是你机器上的4个字节.因此,缓冲区的前四个字节然后在循环中打印.

将它dpBuf声明为更大的数组并不重要,因为它作为指针传递给函数.要避免此问题,您应该向函数添加一个参数,其中显式传递缓冲区的大小.

  • 无论你使用什么检查工具,都可能假设const char*的内容是一个C字符串,因此尊重"C字符串以\ 0字节结尾"规则,以避免在字符串结尾后显示字符,通常是垃圾. (10认同)