2010-03-03 63 views
1

這讓我非常沮喪。我只是試圖創建一個共享內存緩衝區類,該類使用通過Boost.Interprocess創建的共享內存來讀取/存儲數據。我寫了下面的測試功能boost.interprocess中共享內存中的memcpy的問題

#include <boost/interprocess/shared_memory_object.hpp> 
#include <boost/interprocess/mapped_region.hpp> 
#include <iostream> 
using namespace std; 
using namespace boost::interprocess; 

int main(int argc, char* argv[]) { 
    shared_memory_object::remove("MyName"); 
    // Create a shared memory object 
    shared_memory_object shm (create_only, "MyName", read_write); 
    // Set size for the shared memory region 
    shm.truncate(1000); 
    // Map the whole shared memory in this process 
    mapped_region region(shm, read_write); 
    // Get pointer to the beginning of the mapped shared memory region 
    int* start_ptr; 
    start_ptr = static_cast<int*>(region.get_address()); 

    // Write data into the buffer 
    int* write_ptr = start_ptr; 
    for(int i= 0; i<10; i++) { 
     cout << "Write data: " << i << endl; 
     memcpy(write_ptr, &i, sizeof(int)); 
     write_ptr++; 
    } 

    // Read data from the buffer 
    int* read_ptr = start_ptr; 
    int* data; 
    for(int i= 0; i<10; i++) { 
     memcpy(data, read_ptr, sizeof(int)); 
     cout << "Read data: " << *data << endl; 
     read_ptr++; 
    } 

    shared_memory_object::remove("MyName"); 
    return 0; 
} 

當我運行它,它寫入數據確定,但段錯誤在讀取循環第一memcpy。 gdb說以下內容:

程序接收到的信號EXC_BAD_ACCESS,無法訪問內存。 原因:KERN_INVALID_ADDRESS在地址:0x0000000000000000 0x00007fffffe007c5在__memcpy()

(GDB)其中

#0 0x00007fffffe007c5在__memcpy() #1 0x0000000100000e45在主(的argc = 1,的argv = 0x7fff5fbff9d0)在試.cpp:36

功能非常簡單,我不知道我錯過了什麼。任何幫助都感激不盡。

回答

6

data沒有被設置指向任何東西。 (確保程序正在編譯時啓用了所有警告。)它看起來應該不是指針。

第二循環也許應該是:

int* read_ptr = start_ptr; 
int data; 
for(int i= 0; i<10; i++) { 
    memcpy(&data, read_ptr, sizeof(int)); 
    cout << "Read data: " << data << endl; 
    read_ptr++; 
} 
+0

(臉紅),這讓我感覺很濃密!我似乎患有TIQL(暫時的智商損失)(我希望它是暫時的)。 謝謝! – recipriversexclusion 2010-03-03 21:21:37

0

我不能在這裏測試它,因爲我沒有boost可用做,但我有一個猜想。在此example, shared_memory_object對象首先用於寫有標記create_only

shared_memory_object shm (create_only, "MySharedMemory", read_write); 

然後讀取與第二shared_memory_object對象與標誌open_only

shared_memory_object shm (open_only, "MySharedMemory", read_only); 

看來你必須改變你的shared_memory_object到正確的標誌。