Quantcast
Channel: How does shmget allocate memory? Cannot access with linear addressing (Address Boundary error) - Stack Overflow
Viewing all articles
Browse latest Browse all 2

How does shmget allocate memory? Cannot access with linear addressing (Address Boundary error)

$
0
0

In the following example, I'm trying to use shmget to allocate memory for one integer, and 10 foo structs and trying to access them linearly. However, it errors out with an "Address Boundary error".

For a MacOS system (but should be the same on Linux), I tried to allocate the exact amount of memory the two data structures should have taken and tried to byte address them linearly.

#include <stdio.h>
#include <sys/shm.h>

typedef struct {
  int f1;
  int f2;
} foo;

int main() {
  // Size of memory. Consider, int size to be 4. (4 + 8 * 10 = 84 bytes)
  const int shmsz = sizeof(int) + sizeof(foo) * 10; 

  // Create shared mem id.
  const int shmid = shmget(IPC_PRIVATE, shmsz, 0666);
  if (shmid < 0) {
    perror("shmget failed.");
    return 1;
  }

  // Pointer to the shared memory. Cast as char* for byte addressing.
  char* shmemPtr = (char*) shmat(shmid, 0, 0);
  if (*shmemPtr == -1) {
    perror("shmat failed.");
    return 1;
  }

  // The integer should point to the first 4 bytes. This is the same as
  // the address pointed to by shmemPtr itself.
  int* iPtr = (int*) shmemPtr[0];

  // The 80 bytes for the 10 foos range from index 4 -> 83
  foo* fPtr = (foo*) ((void*) shmemPtr[sizeof(int)]);

  printf("i: %p\n", iPtr); // why is this 0x0 ?
  printf("x: %p\n", fPtr); // why is this 0x0 ?

  *iPtr = 0; // <-- This dereference crashes, probably since the address of iPtr is 0x0
}

After allocating the memory and receiving a pointer to it via shmat, any pointers I try to create to the allocated memory is 0x0 and any derefences will (rightfully) crash the program. I expected the int* and foo* to be valid pointers to shared memory.

I'm just dabbling with some systems stuff with C/C++ so forgive me if I'm trivially missing anything here.


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images