I have a program to read the names of files in a directory. The code runs in the CodeBlocks IDE but the same gives me a Debug Assertion Error when I run it in Visual Studio.
I have added _CRT_SECURE_NO_WARNINGS in the Preprocessor properties because without it strerror() gave me an error.
#include <windows.h>
#include <stdio.h>
void listdirs(wchar_t *dir, wchar_t *mask)
{
wchar_t *fspec1 = { L'\0' }, *fname = { L'\0' };
WIN32_FIND_DATA dta;
HANDLE hDta;
DWORD dLastError;
LPCWSTR fspec = reinterpret_cast<LPCWSTR>(fspec1);
char *buff = { '\0' };
swprintf(fspec1, 100, L"%s/%s", dir, mask);
if ((hDta = FindFirstFile(fspec, &dta)) == INVALID_HANDLE_VALUE) {
dLastError = GetLastError();
printf("The error : %s\n", strerror(dLastError));
}
else {
do {
if (!(dta.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
printf("%ws\n", dta.cFileName);
}
else
{
if (wcscmp(dta.cFileName,L".") !=0 && wcscmp(dta.cFileName,L"..")!=0)
{
swprintf(fname, 100, L"%s", dta.cFileName);
listdirs(fname, mask);
}
}
} while (FindNextFile(hDta, &dta));
FindClose(hDta);
}
}
int main (int argc, char *argv[])
{
listdirs(L"C:\\windows\\system32\\Tasks", L"\\.*");
return 0;
}
The output should either print an error message if it cannot access the folder or print the filenames. In either case, I only get a debug assertion error.
With the definitions
wchar_t *fspec1 = { L'\0' }, *fname = { L'\0' };
you say that both fspec1
and fname
are pointers, pointing to NULL
. Attempting to dereference these pointers in any way will lead to undefined behavior.
And you do dereference these pointers, and even attempt to write to where these null-pointers are pointing. For example with
swprintf(fspec1, 100, L"%s/%s", dir, mask);
You need to allocate memory for these pointers to actually point to. Or define them as suitably sized arrays:
wchar_t fspec1[100], fname[100];