0

EDIT: Thanks to Ipmcc, he has given me a solution in the comments.

I would like to use memset to allocate a four-byte address into the first four bytes of memory that I have dynamically allocated. An example with comments of what I'd like to do is shown below. All of my attempts to find out how to do this or figure it out myself has ended up without success.

Any help would be most appreciated, thank you.

int main(void)
{
  // Define and assign eight bytes of memory
  unsigned char *data1 = new unsigned char [8];
  unsigned char *data2 = new unsigned char [8];

  // Set all eight bytes in both data1 and data2 to 0x00
  memset(data1, 0x00, 8);
  memset(data2, 0x00, 8);

  // Lets say that the address of *data1 is: 00508d30
  // Lets say that the address of *data2 is: 0050b180

  // I want to set the first four bytes in data1 to the
  // address of data2, so it would look something like this...
  memset(data1, 0x00, 1); ++data1;
  memset(data1, 0x50, 1); ++data1;
  memset(data1, 0xB1, 1); ++data1;
  memset(data1, 0x80, 1);
  data1 -= 3; // Reset pointer

  // But of course this is in no way practical or viable
  // since the addresses change each time (also it's not a good
  // practice to hard-code things in anyway). So I'm wondering
  // if there's a proper/feasible way to do this.

  return 0;
}
Tundra Fizz
  • 473
  • 3
  • 10
  • 25
  • 1
    Am I missing something here? Or are you making this WAAAAY harder than it needs to be? Can't you just do this the easy way? i.e. `void** foo = reinterpret_cast(data1); *foo = theAddress;` – ipmcc Sep 17 '13 at 01:47
  • I had completely forgotten about reinterpret cast, your way works perfectly; thank you very much! – Tundra Fizz Sep 17 '13 at 01:50
  • 1
    I'm pretty sure you could also use `unsigned char *data1 = new unsigned char[8]{0};` and `new unsigned char[8]();` to create an array of zero-initialized characters. – dyp Sep 17 '13 at 01:54
  • 1
    Even simpler: `reinterpret_cast(data1) = theAddress;`. – MSalters Sep 17 '13 at 06:19

0 Answers0