1

C++ has a neat feature where you can create an object at a specific memory address as shown here.

This is particularly useful with mmap like so:

void *ptr = mmap(0, length, prot, flags, fd, offset);

A *ptrA = new (ptr) A;

What is the correct way to replicate this with just C-style structs? Would it just be this?

void *ptr = mmap(0, sizeof(A), prot, flags, fd, offset);

A *ptrA = (A*) ptr;
sj95126
  • 6,520
  • 2
  • 15
  • 34
knowads
  • 705
  • 2
  • 7
  • 24
  • You just set the address and treat it as though it was the struct. C doesn't verify that you're using any memory correctly. Usually writing to a specific address is used to write to hardware registers. – Ouroborus Nov 01 '21 at 04:06
  • What you have as shown, casting the the pointer returned from mmap as a pointer to the desired type, is spot on. – selbie Nov 01 '21 at 04:17
  • 3
    FYI the explicit cast in C is unnecessary as a void pointer can be assigned to a pointer variable of any type: `A *ptrA = ptr;` – kaylum Nov 01 '21 at 04:22
  • 1
    @kaylum: Any object type, not any type. – Eric Postpischil Nov 01 '21 at 08:05

1 Answers1

0

This is valid because no memory usage constraints are enforced in C.

void *ptr = mmap(0, sizeof(A), prot, flags, fd, offset);

A *ptrA = (A*) ptr;
knowads
  • 705
  • 2
  • 7
  • 24
  • 1
    Good for answering your own questions. Note, as mentioned in the comments, `A *ptrA = ptr;` is fine without the cast as `ptr` has `void*` type and in C a pointer and be assigned to/from `void*` without a cast. – David C. Rankin Feb 10 '22 at 04:28