Search code examples
carraysrtos

static array is changed to dynamic for a mmaped structure


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


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.