我的结构包含像这样的数组元素
#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;
}
正如您所看到的,我使用mmap
在共享内存区域上分配此tempstruct
的实例,但由于某些更改,我想动态分配tempstruct
结构的数组元素为SIZE
不会是编译时间常量。那么上面的程序仍然有效吗?我可以在堆上分配数组然后mmap
将它分配给共享内存,那么另一个进程中的数组是否指向同一堆区域?我想没有,请建议一些更好的方法吗?
由于
答案 0 :(得分:2)
以下是解决此问题的一种方法:
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);
...
}
请注意,您将无法正确使用tempstruct
个实例数组。
答案 1 :(得分:0)
malloc的内存块属于执行malloc的进程,而另一个进程不会访问相同的内存(并可能导致异常)。
如果您不使用GCC或强制执行ISO C,请使用zero length array或长度为1的数组,只需创建mmap块sizeof tempstruct + size of array。因为C不对数组执行边界检查,所以可以访问结构外部的内存,就好像它是结构末尾的数组一样。
此技术仅在array
是结构的最后一个成员且结构未嵌套在具有以下成员的其他结构中时才有效。由于tempstruct
是一个匿名结构,因此无论如何都不能这样做。