1

I'm attempting to use boost's shared memory library to do some inter-process communication (VS 2015). I found an example online which is very helpful. For sanity's sake I just want to perform a simple check that the value I wrote to the shared memory address is what I wanted. To do this I want to print the value of the shared memory using cout. This is the code I have currently:

#include <boost\interprocess\shared_memory_object.hpp>
#include <boost\interprocess\mapped_region.hpp>
#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <cstring>
#include <cstdlib>
#include <string>

int main()
{
    using namespace boost::interprocess;

    struct shm_remove
    {
        shm_remove() { shared_memory_object::remove("MySharedMemory"); }
        ~shm_remove() { shared_memory_object::remove("MySharedMemory"); }
    } remover;

    //Create a shared memory object
    shared_memory_object shm(create_only, "MySharedMemory", read_write);

    //Set size to 1
    shm.truncate(1);

    //Map the whole shared memory in this process
    mapped_region region(shm, read_write);

    //Write all the memory to 1
    std::memset(region.get_address(), 1, region.get_size());

    //Check that memory was initialized to 1
    char *mem = static_cast<char*>(region.get_address());

    for (std::size_t i = 0; i < region.get_size(); ++i)
    {
        std::cout << "Memory value: " << *mem << "\n";
        if (*mem++ != 1)
        {
            return 1;   //Error checking memory
        }
    }
    std::cout << "press any key to quit";
    _getch();
}

The code works fine, no errors are thrown when it checks that the mapped memory has been set to 1. However when I try to print what I think should be the value at the address, I get a smiley face...

enter image description here

Can anyone point me in the right direction? I have some suspicions (no terminating \0?) but I really don't understand the inner workings here. Any help is appreciated!

willpower2727
  • 769
  • 2
  • 8
  • 23

2 Answers2

3

Cast mem to int explicitly, then std::cout is going to output the value as a number, not as a letter corresponding to the ASCII code stored inmem (which may be unprintable or look funny, the latter being your case).

See cout not printing unsigned char for a more thorough answer on the problem.

Community
  • 1
  • 1
iksemyonov
  • 4,106
  • 1
  • 22
  • 42
2

The console shows you the ASCII representation of bytes in memory. Any character under 13 is usually unprintable. Try setting the memory to something like 67.