【问题标题】:many buffers in char bufferchar 缓冲区中的许多缓冲区
【发布时间】:2012-05-27 00:36:20
【问题描述】:
int main(int argc, char **args) {
    unsigned char* str = "hallo";
    printf("String: %s\n",str);
    uint8_t aktion, id;
    uint32_t str_length;
    aktion = 1;
    id = 4;
    str_length = strlen(str)+1;

    unsigned char *buff;    
    buff = (unsigned char*) calloc(1,str_length+6);
    memcpy(buff, &id, sizeof(id));
    memcpy(buff+sizeof(id), &str_length, sizeof(str_length));
    strcpy(buff+sizeof(id)+sizeof(str_length), str);
    printf("Buffer+5: %s\n",buff+5));
    memcpy(buff+sizeof(id)+sizeof(str_length)+str_length, &aktion, sizeof(aktion));
    return 0;
}

为什么我没有得到输出“你好”?我仍然不确定是否使用指针算法和缓冲区。

问候

【问题讨论】:

  • 鉴于您转换calloc 的结果的方式,我认为这是C++。你应该使用std::string,而不是乱用裸指针。
  • 那么你不应该投射calloc的结果。
  • 另外,赤裸裸的15 很奇怪。如果您已经知道尺寸,为什么还要打扰sizeof?最好的办法是在任何地方都写 sizeof 并且没有幻数,并将 sizeof(uint8_t) 替换为 sizeof id 等。
  • 为什么,你能给我一些背景资料吗?省略演员表没有帮助。
  • 不,它没有帮助,它只是更好的 C。这就是为什么它是一个评论 :-)

标签: c pointers char buffer void


【解决方案1】:
uint32_t str_length;
aktion = 1;
id = 4;
str_length = strlen(str)+1;

unsigned char *buff;    
buff = (unsigned char*) calloc(1,str_length);

您不应该在 C 中强制转换 malloc/calloc 的返回指针。

您的buff 大小为 6

memcpy(buff, &id, sizeof(uint8_t));

你在这里写了 1 个字节

memcpy(buff+1, &str_length, sizeof(uint32_t));

你在这里写了 4 个字节:

这意味着您已用尽分配给buff 的 6 个字节中的 5 个字节

strcpy(buff+5, &str);

您正在为 buff 写入分配的字节。这会导致内存损坏

【讨论】:

  • 啊,好吧,缓冲区大小是错误的。改变了,现在它工作了!谢谢
【解决方案2】:

应该是:

strcpy(buff + sizeof id + sizeof str_len, str);
/*                                        ^^^^   no '&'!  */

str 已经是一个指针。相比之下,&str 是指针的地址,这不是你想要的。

您还需要在缓冲区中为两个初始变量腾出空间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多