title: Initializing shared memory using mmap() for a 2D array, is it necessary to also map memory for subsequent pointers? Should I use shm instead?
body: <p>I am using <code>mmap()</code> to initialize a shared memory space for parent and child processes and the object happens to be a double char pointer (i.e. <code>char**</code>). It's necessary because I'm going to be storing user input to this 2D array in a child process and the parent will be accessing this same data after the child has terminated. It wasn't hard to work this out after reading a little bit of documentation on <code>mmap()</code>, and it feels a lot like <code>malloc()</code>, but less of a commitment.</p>
  
  <p>Consider the code below, copied directly from the program I'm writing:</p>
  
  <pre><code>/* mmap prot and flags */
  int protection = PROT_READ | PROT_WRITE;     // readable and writable
  int map_flags  = MAP_SHARED | MAP_ANONYMOUS; // no file, changes are propagated
  
  /* initialize shared memory */                 
  char **histv = (char**)mmap(NULL,              // (void*)  address
                  (sizeof(char*) * MAX_HISTORY), // (size_t) length
                  protection,                    // (int)    memory protection
                  map_flags,                     // (int)    mapping flags
                  -1,                            // (int)    file descriptor
                  0);                            // (off_t)  addr offset
  
  for (int i = 0; i &lt; MAX_HISTORY; i++) {
      histv[i] = (char*)mmap(NULL,  
                  (sizeof(char) * MAX_LINE), 
                  protection,
                  map_flags, 
                  -1, 
                  0);
  }
  </code></pre>
  
  <p>My questions:</p>
  
  <ol>
  <li><p>Must I loop through the array of pointers to map each subsequent address in the array or do I really only need the pointer returned from the first mapping?</p></li>
  <li><p>If it is not required, is it recommended to do it anyways? </p></li>
  <li><p>Is there any practical reason to always use <code>shm_open()</code> and <code>ftruncate()</code> in conjunction with <code>mmap()</code> instead of using <code>MAP_ANONYMOUS</code>? (note: I have never used the former two, I've just recently been reading a lot about shared memory.)</p></li>
  </ol>