Re: place stl container object on shared memory
Jeff Schwab raised a very good point, that you shouldn't delete an
object created with a placement new. I think maybe deleting the
vector corrupted the heap, which may have caused the run-time error in
the String constructor.
As I V pointed out STL containers dynamically allocate additional
memory. Using the default STL allocator, this additional memory will
not be in the shared memory region.
So you could use (generally more primitive) containers that don't
dynamically allocate memory. Like arrays or boost intrusive
containers. This, http://www.geocities.com/wkaras/gen_cpp/avl_tree.html
, could be used as a rough substitute for the map and set templates.
If you are willing to take on a big challenge, you could write (or
maybe find?) an STL-compatible allocator that uses shared memory. To
write such an allocator, this, http://www.geocities.com/wkaras/heapmm/heapm=
m.html
, might be helpful.
On Feb 24, 3:13 pm, dbtouch <dbto...@gmail.com> wrote:
Hi, C++ programmers
I am trying to place an STL container object on shared memory and I
got a Segmentation Fault. Please give me some advice. Please notice
that if I allocate memory locally then I can place pStr on the
address
I sepcify. My platform is SunOS 5.10.
dbtouch
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <string>
#define CHECK_RESULT(X, Y) \
if (X==-1) \
{ \
perror(Y); \
exit(EXIT_FAILURE); \
}
typedef std::vector<int> VecInt;
typedef std::string String;
int main() {
// create shared memory
int result=shmget(IPC_PRIVATE, 1024*1024, 0644 | IPC_CREAT);
if (result==-1) {
perror("shmget");
exit(EXIT_FAILURE);
}
int shmid=result;
// attach shared memory
char *ptr=NULL;
ptr=(char*)shmat(shmid, NULL, 0644);
if ((int)ptr==-1) {
perror("shmat");
exit(EXIT_FAILURE);
}
#if 0
VecInt* pVec=new(ptr)VecInt(10);
delete pVec;
#endif
// char* qtr=new char[1024*1024];
// String* pStr=new(ptr)String(); good
String* pStr=new(ptr)String(); // segment fault!!!
if (pStr) {
delete pStr;
printf("test is good\n");
}
result=shmdt(ptr);
CHECK_RESULT(result, "shmdt")
result=shmctl(shmid, IPC_RMID, NULL);
CHECK_RESULT(result, "shctl")
exit(EXIT_SUCCESS);
}