tags:

views:

262

answers:

3

I'm supposed to write a library in c++ that should handle the connections to the kad network. I'm trying to build a packet accordant to those used by 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)

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...

and why in the constructor of a class can't I modify a [private] "char* buffer" like this:

buffer[0] = 0xe4;

? (it does not work, exits without any trace back error)

(if it can matter, I'm using crypto++ and boost libraries)

thanks in advance for any help_

+6  A: 

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. 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.

bdonlan
ok. the matter was in that "static" keyword.thanks a lot.
paolo_
Don't just toss in "static" without knowing what it implies - if you have multiple instances of this class, recursion, or multiple threads, you'll likely end up with data corruption, because you'll be sharing the same buffer in more than one place. I'd give better advice but you've been too non-specific about your program to give any concrete suggestions.
bdonlan
+2  A: 

"" literals have implicit NUL termination unless constrained by an explicit array length (not in this case).

Also in the second case, since p_buffer is a local variable i.e. 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.

laalto
+2  A: 

Just a suggestion - if you're already using Boost, look into boost::array for simplified fixed-length buffer management, and into boost::shared_array for dealing with variable-length buffers.

Nikolai N Fetissov