Question

I have a structure which contains an array elements like this

    #define SIZE 20
    typedef struct
    {
        int currentindex;
        int array[SIZE];
    } tempstruct;

    int main()
    {
        int fd;
        tempstruct *ptr = NULL;
        fd = shm_open("/TESTPROG", O_RDWR | O_CREAT, 0666);
        ptr = mmap(0,sizeof(tempstruct),PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
        /* 
        So in case SIZE is not compile time constant but another int then I do this
        ptr = mmap(0,sizeof(tempstruct),PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
        ptr.array = (int*)malloc(sizeof(int)*SIZE);
    */
        return 0;
    }

As you can see that I use mmap to allocate instance of this tempstruct on shared memory area but now due to some changes I want to dynamically allocate array element of tempstruct structure as SIZE will not be compile time constant. So will above program be still valid ? like can I allocate array on heap and then mmap'ed it to shared memory so will array in another process points to same heap area ? I guess no so please suggest some better ways ?

Thanks

Was it helpful?

Solution

Here is one way to solve this:

typedef struct
{
    int currentindex;
    int array[0];
}
tempstruct;

int main()
{
    ...
    int totalSize = sizeof(tempstruct) + sizeof(int) * numOfElements;
    ptr = mmap(0, totalSize, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
    ...
}

Please note that you will not be able to properly utilize an array of tempstruct instances.

OTHER TIPS

The malloc'ed memory block would belong to the process that performed the malloc, and the other process would not access the same memory (and may cause an exception).

Use a zero length array, or an array of length 1 if you are not using GCC or enforcing ISO C, and simply create the mmap block sizeof tempstruct + size of array. Because C does not perform bounds checking on arrays, you can access the memory outside teh structure as if it were an array at the end of the structure.

This technique will only work if array is the last member of the struct, and the struct is not nested in some other struct with following members. As tempstruct is an anonymous struct, you cannot do that in any case.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top