diff --git a/winpr/libwinpr/environment/environment.c b/winpr/libwinpr/environment/environment.c index 600b15f20..84743e061 100644 --- a/winpr/libwinpr/environment/environment.c +++ b/winpr/libwinpr/environment/environment.c @@ -24,12 +24,15 @@ #include #include #include +#include #include #include #ifndef _WIN32 +#include + #ifdef WINPR_HAVE_UNISTD_H #include #endif @@ -43,20 +46,35 @@ DWORD GetCurrentDirectoryA(DWORD nBufferLength, LPSTR lpBuffer) { - char* cwd = NULL; size_t length = 0; + char* cwd = NULL; + char* ccwd = NULL; - cwd = getcwd(NULL, 0); + do + { + length += MAX_PATH; + char* tmp = realloc(cwd, length); + if (!tmp) + { + free(cwd); + return 0; + } + cwd = tmp; - if (!cwd) + ccwd = getcwd(cwd, length); + } while (!ccwd && (errno == ERANGE)); + + if (!ccwd) + { + free(cwd); return 0; + } - length = strlen(cwd); + length = strnlen(cwd, length); if ((nBufferLength == 0) && (lpBuffer == NULL)) { free(cwd); - return (DWORD)length; } else