c - 写入分配的字符缓冲区

标签 c char

我有以下代码:

framingStatus compressToFrame(char* inputBuffer, size_t inputBufferLength, char* frame, size_t* frameLength)
{
    dword crc32 = GetMaskedCrc(inputBuffer,inputBufferLength);
    size_t length = snappy_max_compressed_length(inputBufferLength);
    char* compressed = (char*)malloc(length);
    snappy_status status = snappy_compress(inputBuffer,inputBufferLength,compressed,&length);
    if( status!=SNAPPY_OK )
        return FS_ERROR;
    frame[0] = 0x00; // Typ ramki skompresowany
    frame[1] = length&0xff;
    frame[2] = (length&0xff00)>>8;
    frame[3] = (length&0xff00)>>16;
    frame[4] = crc32&0xff;
    frame[5] = (crc32&0xff00)>>8;
    frame[6] = (crc32&0xff0000)>>16;
    frame[7] = (crc32&0xff000000)>>24;
    frame[8] = '\0'; // Pomoc dla strcat

    strcat(frame,compressed);
    *frameLength = length+8;
    free(compressed);

    return FS_OK;
}

在调用这个函数之前,我为名为 frame 的缓冲区分配了内存。一切正常,但分配指令 frame[x] = ... 似乎没有向称为 framestrcat 连接的缓冲区写入任何内容压缩数据到没有我需要的标题的空缓冲区。

为什么赋值指令frame[x] = ...等不给出任何结果?

[编辑:] 如果我想将帧头与压缩数据连接起来,你能建议我必须使用什么函数吗?

[编辑2:] 下面显示的代码工作得很好。

framingStatus compressToFrame(char* inputBuffer, size_t inputBufferLength, char* frame, size_t* frameLength)
{
    dword crc32 = GetMaskedCrc(inputBuffer,inputBufferLength);
    size_t length = snappy_max_compressed_length(inputBufferLength);
    char* compressed = (char*)malloc(length);
    snappy_status status = snappy_compress(inputBuffer,inputBufferLength,compressed,&length);
    if( status!=SNAPPY_OK )
        return FS_ERROR;
    frame[0] = 0x00; // Typ ramki skompresowany
    frame[1] = length;
    frame[2] = length >> 8;
    frame[3] = length >> 16;
    frame[4] = crc32;
    frame[5] = crc32 >>8;
    frame[6] = crc32 >>16;
    frame[7] = crc32 >>24;

    memcpy(&frame[8],compressed,length);
    *frameLength = length+8;
    free(compressed);

  return FS_OK;
}

最佳答案

你有

frame[0] = 0x00;

相同
frame[0] = '\0';

无论您在第一个字符后添加什么,frame 都会变成一个0 长度的字符串。

关于c - 写入分配的字符缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22966788/

相关文章:

c - 如何在 CLion 中自动生成和更新 .h 文件的函数声明(原型(prototype))?

有人可以帮我完成 C 编程任务吗?

c++ - 24 位工具栏按钮图像? (WinAPI)

binary - 如何转换二进制!到一个字符!在《叛逆2》中?

c - 在c中的字符串左侧添加空格

c++ - 将整数转换为字符缓冲区以进行串行通信...?

c - 十六进制 uint32_t 的 printf() 格式,不丢失零。 (在 c89 中)

有人可以帮助我理解为什么我在下面的程序中遇到段错误

c++ - char& operator[] 重载引用返回? (链表)

关于 char** 参数的 const char** 参数警告