Search code examples
cmemorystructsharedmmap

Segmentation fault when accessing shared memory in C


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?


Solution

  • 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];
    };