Why do you limit the size of expanded string to MAX_PATH? It would probably be better to follow the pattern of calling ExpandEnvironmentStringsW with NULL to have it compute the required length before allocating the memory and calling Expand... again with appropriately sized buffer.