2

I have 2 programs which need to share memory. Let's call one program A, the other one B.

There is a struct in this format for this purpose:

struct town_t {
    int population;
    char * name; 
}

In program A, data gets written to shared memory using mmap. This works for program A. (It uses strcpy for the name)

Program B's purpose is to simply read the data. This too works with mmap. Accessing the shared memory's population field works without any problems. However, accessing the population field gives a segmentation fault.

Since I used strcpy, the entire string should be in the shared memory right?

I use the following flags to get the pointer to shared memory, which returns no error.

tptr = (struct town_t *) mmap(0, 1024, PROT_READ, MAP_SHARED, shm_fd, 0)

How could I make it so I can actually read the string (char*) from program B?

5
  • 1
    Using strcpy has nothing to do with whether the string is in shared memory. What memory does name point to and how did you allocate that memory? Commented Dec 7, 2016 at 23:30
  • @immibis I am using strcpy to the shared memory pointer. I allocate with char * str = "string". Commented Dec 7, 2016 at 23:49
  • So you do tptr = mmap(...); char *str = "string"; strcpy(tptr->name, str);? Commented Dec 8, 2016 at 2:31
  • @immibis Well that won't work because tptr->name has no particular value, so you're passing garbage (likely NULL) to strcpy. Commented Dec 8, 2016 at 7:50
  • @DavidSchwartz I know why it won't work. I asked the asker if that is what the asker has written. Commented Dec 8, 2016 at 9:08

1 Answer 1

1

There's no point in putting a pointer in shared memory. A pointer gives a location inside the address space of a particular process. It would have no meaning to another process with another address space. (With some complicated exceptions such as a pointer to memory allocated before a call to fork accessed by related processes running the same executable.)

You can store the string data itself in shared memory if you wish. For example, this will work:

#define MAX_NAME_SIZE 100

struct town_t
{
    int population;
    char name[MAX_NAME_SIZE];
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.