title: WINAPI C - CreateFileMapping fails with error 8 - ERROR_NOT_ENOUGH_MEMORY
body: <p>I'm working with file mappings on Windows but having some troubles with them.
  First off, I have the necessity to partially map a file and setting the start and the end of it dynamically.</p>
  
  <p>My code is the following:</p>
  
  <pre><code>long fiveMB = 5 * pow(2, 20);
  for(int i=0;i&lt;parts;i++){
      long start = (i)*fiveMB;
      long end = (i + 1)*fiveMB;
      long realEnd = end;
      if (roundedDim&lt;realEnd)
          realEnd = dim;
  
      long chunkDim = realEnd - start;
      LARGE_INTEGER fileMapStart.QuadPart = (start/granularity)*granularity;
      LARGE_INTEGER mapViewSize.QuadPart = (start%granularity) + chunkDim;
      LARGE_INTEGER fileMapSize.QuadPart = start + chunkDim;
      long offset = start - fileMapStart.QuadPart;
  
      HANDLE fileMappingH= CreateFileMapping(fileH, NULL, PAGE_READONLY, fileMapSize.HighPart, fileMapSize.LowPart, NULL);
  
      if(fileMappingH == INVALID_HANDLE_VALUE || fileMappingH == NULL){
         printf("Error mapping file: %d\n",GetLastError());
         CloseHandle(fileH);
         return 1;
      }
  
      char *mapView = (char *)MapViewOfFile(fileMappingH, FILE_MAP_READ, fileMapStart.HighPart, fileMapStart.LowPart, mapViewSize.QuadPart);
      if ((LPVOID)mapView == NULL) {
          printf("Error mapView: %d\n", GetLastError());
          CloseHandle(fileMappingH);
          CloseHandle(file);
          return 1;
      }
  
      mapView += offset;
  
      /* doing all the stuff */
  
      UnmapViewOfFile((LPVOID)mapView);
      CloseHandle(fileMappingH);
  }
  </code></pre>
  
  <p>As far as I know, only MapViewOfFile requires the starting byte to be aligned with the system granularity, so I didn't bother to fix the maximum file mapping size for that.</p>
  
  <p>I tried this code on a 1448 KB file (printing out dim I get <strong>1482159 bytes</strong>) while calculating the available memory via GlobalMemoryStatusEx(&amp;memstatus) and <strong>memstatus.ullAvailVirtual</strong> I get <strong>2092208128 bytes</strong> but still stuck on having the CreateFileMapping call failed and with error code 8, <code>ERROR_NOT_ENOUGH_MEMORY</code>.</p>
  
  <p>I also tried calling <strong>CreateFileMapping(fileH, NULL, PAGE_READONLY, 0, 0, NULL)</strong> to memory map the whole file, but instead there were problems on <strong>MapViewOfFile</strong>, error 5, <code>ERROR_ACCESS_DENIED</code>.</p>
  
  <p>I don't understand what I'm doing wrong here, since I successfully did it with mmap on a Linux version of the same project.</p>
  
  <p>Thanks anyone who may help.</p>
  
  <hr>
  
  <p>EDITS:</p>
  
  <ul>
  <li><p>c was a leftover, I actually meant i</p></li>
  <li><p>added UnmapViewOfFile and CloseHandle calls</p></li>
  </ul>