[help] Adding to a Existing Buffer

Posts 1–2 of 2 · Page 1 of 1
[help] Adding to a Existing Buffer
My brain isnt working for some reason and i dont know what is wrong...

I'm trying to add a header to this buffer once the buffer has been determined.

EXAMPLE: 00 00 00 00 = 4 bytes wich is the size i would then add +2 to make it 6..

so the new buffer would be 06 00 00 00 00 00

Code:
usigned int Size;
unsigned char * newbuffer = new unsigned char[ Size + 2 ];

int m = Size + 2;

// copy data from the Buffer to newbuffer  
memcpy( newbuffer + 2 * sizeof( unsigned char ), Buffer, sizeof( unsigned char ) * Size );

// swap buffers
delete [] Buffer;
Buffer = newbuffer;
Size = m;
this seems to work but the new buffer just gives junk data in the array..

like... 45 23 00 00 00 00 = 6 size....

instead of it being 06 00 00 00 00 00
Code:
unsigned int Size;
unsigned char * newbuffer = new unsigned char[ Size + 2 ];
Size will be whatever is stored in memory(so random untill you initialize it as something)

Also, an int is 4 bytes, so if you only want a two byte header use
Code:
unsigned short Size = reinterpret_cast<unsigned short>(sizeof(Buffer));
Now, to allocate memory you could use malloc(size)
So your code will be something along the lines of this:
Code:
char *buffer = malloc(Size+2);
buffer[0] = Size;
memcpy(buffer[2], oldBuffer, Size);
Make sure to initialize Size though(or allocate memory for the new buffer AFTER you used sizeof(oldbuffer)
Posts 1–2 of 2 · Page 1 of 1

Post a Reply

Similar Threads

Tags for this Thread

None

Talk with us