Search code examples
c++cpointersmemcpymemset

Cannot write integer to an offset within a buffer (char*)


I'm trying to write an unsigned integer to a specific offset in buffer in my C program. The buffer is typical 1 byte char * buffer. I'm using memcpy to do this with some pointer arithmetic to point memcpy destination to a particular offset withing that buffer.

Code:

char* ph = (char*) malloc(4096);

//Init buffer with '\0'
memset(ph, '\0', 4096);

//Set int to be written
unsigned int tupleCnt = 4;

//Write to 4th byte offset (int* + 1)
memcpy(((int*) ph) + 1, (void *) &tupleCnt, sizeof(tupleCnt));

However, this doesn't write anything to this buffer.

Here's the hexdump of the file to which this buffer is written:

0000000 0000 0000 0000 0000 0000 0000 0000 0000
               ^

If I write it to 0th offset, it works:

//Write to 0th byte offset (int* + 0)
memcpy(((int*) ph) + 0, (void *) &tupleCnt, sizeof(tupleCnt));

Here's the hexdump:

0000000 0004 0000 0000 0000 0000 0000 0000 0000
          ^

By the way I'm using fwrite to write this buffer to file, if it makes any difference.

fwrite(ph, 1, strlen(ph), fp);

I also tried using byte by byte increment on char* pointers, it didn't help either. For example:

//Write to 4th byte offset (int* + 1)
memcpy(ph + 4, (void *) &tupleCnt, sizeof(tupleCnt));

Thanks in advance! Or is there any other way to write int (or any numeric) values to char* buffers? Except int to string conversation, which I really want to avoid. I think it's too much overhead and naive method. :)


Solution

  • You problem not in memcpy but in the way you write to file:

    fwrite(ph, 1, strlen(ph), fp);
    

    this code write 0 bytes, because of strlen return count of bytes from begin to first '\0' in your case it zero bytes.