title: How to read Import Directory Table in C
body: <p>I'm trying to build a PE viewer in C++ and it seems to crash if i try to output the names of the libraries in the Import Directory Table. It seems that I am not getting the correct pointers for the DLLs that are used by the program.</p>
  
  <pre><code>HANDLE handle = CreateFile("messagebox.exe",GENERIC_READ,0,0,OPEN_EXISTING,
                                FILE_ATTRIBUTE_NORMAL,0);
  DWORD size = GetFileSize(handle,NULL);
  PVOID virtualpointer = VirtualAlloc(NULL,size,MEM_COMMIT,PAGE_READWRITE);
  state = ReadFile(handle,virtualpointer,size,&amp;byteread,NULL);
  CloseHandle(handle);
  PIMAGE_NT_HEADERS ntheaders = PIMAGE_NT_HEADERS(PCHAR(vpointer) + 
                                       PIMAGE_DOS_HEADER(vpointer)-&gt;e_lfanew);
  handle = GetCurrentProcess();
  DWORD EntryAddr = ntheaders-&gt;OptionalHeader.ImageBase + 
                         ntheaders-&gt;OptionalHeader.AddressOfEntryPoint;
  
  DWORD importdir = 
         (DWORD) &amp;(ntheaders-&gt;OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]);
  
  DWORD va = (DWORD)(ntheaders-&gt;OptionalHeader.ImageBase) + 
                       ((PIMAGE_DATA_DIRECTORY)dwValueB)-&gt;VirtualAddress;
  LPSTR libname[128];
  int i =0;
  while(((PIMAGE_IMPORT_DESCRIPTOR)dwValueC)-&gt;Name)
  {
         // get DLL name
         libname[i] = (LPSTR)(nt-&gt;OptionalHeader.ImageBase + 
                           ((PIMAGE_IMPORT_DESCRIPTOR)dwValueC)-&gt;Name);
         i++;
  }
  </code></pre>