Padmelina Padmelina - 1 year ago 95
C++ Question

Make content null if shared memory c++

There're struct (Type) and function, that allow to work with struct through shared memory (shm_open and mmap) returns Type*.

Type* type = openSharedMemory();

I want to make content if shared memory null and statement
typeptr == nullptr
should returns true in the process which not create but openSharedMemory memory.
Is it possible?

Answer Source

That's not how pointers work.

If you set a pointer to null the memory still stays there until someone changes it. Even if there is a 0 in the memory this can also just mean an integer 0 for example. This is true for normal pointers in c++ but also for shared memory.

What you need to do is make the memory "invalid". There is no standard to do this in c++ so this has to be defined by yourself.

You have several options here.

One is to define an invalid value for yourself and set the data to this value.

E.g. if you have an int but you know you only store positive numbers in there you can set it to -1 to mark as invalid (or maximum/minimum int, I guess you get the point).

And then you check that instead of the pointer

//in some header
static const int INVALID_VALUE = -1;

//some process
type->shared_int = INVALID_VALUE;

//somewhere else
if(type->shared_int != INVALID_VALUE) //or whatever
    //do stuff

If you have a custom struct in your memory you can add a boolean flag whether it is valid or not

struct Type
    bool valid = true; //c++11 initialize to true
    //other data members

When you now want to mark the memory as invalid just set the member to false and check for that.

//some process
type->valid = false;

//somewhere else
    //do stuff

You can avoid those things if you have clear ownership of the objects when you are using normal pointers.

In interprocess communication that can get a bit complicated so you have to use mechanisms like this.

Design wise it would be better to have one process who is responsible for the memory (allocation and deallocation) and make sure that other process are done or just stop needing to access the memory when you "delete" it. But this is not always possible though.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download