简体   繁体   English

char数组的分配和管理

[英]char array assignment and management

I'm supposed to write a library in c++ that should handle the connections to the kad network. 我应该用c ++编写一个库,该库应该处理与kad网络的连接。 I'm trying to build a packet accordant to those used by aMule&co. 我正在尝试构建与aMule&co使用的数据包一致的数据包。

And I really can't understand the difference between this code: 而且我真的无法理解这段代码之间的区别:

buffer = "\xe4\x20\x02";

and, for example, this code: 并且例如,此代码:

char p_buffer[36];
p_buffer[0] = 0xe4;
p_buffer[1] = 0x20;
p_buffer[2] = 0x02;

buffer = p_buffer;

(buffer is a private attribute of the class, while p_buffer is a local variable) (buffer是该类的私有属性,而p_buffer是局部变量)

capturing the packets with wireshark gives me different results (the first one is right as I wanted, the second one not), like I was doing something wrong with little endian / big endian notations, I guess... 使用Wireshark捕获数据包会给我不同的结果(第一个是我想要的,第二个则不是),就像我用小字节序/大字节序表示法做错了一样,我想...

and why in the constructor of a class can't I modify a [private] "char* buffer" like this: 以及为什么在类的构造函数中无法像这样修改[private]“ char *缓冲区”:

buffer[0] = 0xe4;

? (it does not work, exits without any trace back error) (它不起作用,退出时没有任何追溯错误)

(if it can matter, I'm using crypto++ and boost libraries) (如果可以的话,我正在使用crypto ++和boost库)

thanks in advance for any help_ 在此先感谢您的帮助_

Your first code sample is roughly equivalent to: 您的第一个代码示例大致相当于:

static const char buffer_internal[4] = { 0xe4, 0x20, 0x02, 0x00 };
buffer = buffer_internal;

The two differences here are: 这里的两个区别是:

  • The buffer is null-terminated 缓冲区为空终止
  • The buffer is unmodifiable. 缓冲区不可修改。 Attempting to modify it is likely to crash. 尝试修改它可能会崩溃。

Your second sample allocates a 36-byte modifiable buffer. 您的第二个示例分配一个36字节的可修改缓冲区。 However said buffer will also be discarded when it goes out of scope - be very careful here that it's not used after being freed. 但是,当该缓冲区超出范围时,该缓冲区也将被丢弃-注意此处在释放后不使用。

As for the third sample, have you initialized 'buffer', if it is a pointer? 至于第三个示例,是否已初始化“缓冲区”(如果它是指针)? You've not given enough information to really diagnose your error - the full class declaration and constructor would be helpful. 您没有提供足够的信息来真正诊断错误-完整的类声明和构造函数将很有帮助。

"" literals have implicit NUL termination unless constrained by an explicit array length (not in this case). ""文字具有隐式NUL终止,除非受到显式数组长度的约束(在这种情况下不是)。

Also in the second case, since p_buffer is a local variable ie an automatic variable allocated on the stack, the contents of it are not initialized to zero or anything but will contain whatever junk there is in the underlying stack memory. 同样在第二种情况下,由于p_buffer是局部变量,即在堆栈上分配的自动变量,因此它的内容不会初始化为零或任何东西,而是会包含基础堆栈内存中的任何垃圾。

只是一个建议-如果您已经在使用Boost,请查看boost::array以简化固定长度缓冲区管理,并查看boost::shared_array以处理可变长度缓冲区。

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

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