1

我曾尝试使用 Boost 并在分配 3000 次大小为 24 的对象后使用 segv,现在我开始使用 sys/ipc.h 和 sys/shm.h ,我分配了 25 个 mio 字节(如果我理解正确的话)

它似乎也可以在我的 linux 机器上正常工作 ipcs -m 将显示分配的段

0x000081bc 917516     testUser 644        25000000   0

sysctl -p 将打印

kernel.shmmax = 25500000

由于某种原因,它一直工作到程序达到“43406 x 24 字节”,这就是它将 segv 的地方。我很高兴能得到一些提示我的问题所在。另请注意,如果这是为对象分配和使用共享内存的错误方式。

#define MAXMYMEM 25000000
int sharedMemId;
x *p_sharedMemory;
x *p_other;
sharedMemId = shmget(2232, MAXMYMEM, IPC_CREAT | 0644);

if(sharedMemId >= 0){

    p_sharedMemory = (x*) shmat( sharedMemId, 0 , 0);

    if(p_sharedMemory != ( x *)-1) {

        cout << sizeof(x) << endl;

        for(unsigned int i = 0 ; i < 1000000;i++ ){



            (p_sharedMemory + (sizeof(x) * i))->setTest(i);

        }
4

1 回答 1

2

(p_sharedMemory + (sizeof(x) * i))->setTest(i);

你为什么在这里使用sizeof(x)?向指向 x 的指针添加一个将指向下一个 x,而不是下一个字节。我怀疑这是你的问题。

更改(p_sharedMemory + (sizeof(x) * i))->setTest(i);

++p_sharedMemory;
p_sharedMemory->setTest(i);
于 2012-02-21T20:34:19.067 回答