堆栈在递归函数中溢出

abi*_*ash 0 c++ winapi

我正在编写一个简单的应用程序,将某些目录中的所有文件输出到控制台 为实现这一点,我在函数中动态分配内存PathCreator()并返回指向此内存的指针.我不知道如何正确释放这个内存段GetAllFiles().当我使用下面的代码时,我得到一个堆栈溢出异常.我怎样才能解决这个问题?请不要让我使用不需要动态分配内存的东西,我只是想修复我的代码.

#include "stdafx.h"
#include <windows.h>
#include <iostream>
wchar_t *PathCreator(wchar_t *dir, wchar_t *fileName);
int is_directory(wchar_t *p)
{
    wchar_t *t = PathCreator(p,L"\\");
    WIN32_FIND_DATA file;
    HANDLE search_hendle = FindFirstFile(t, &file);
    long error = GetLastError();
    if(error == 267)
    {
        return 0;
    }
    else
    {
        return 1;
    }
}

wchar_t *PathCreator(wchar_t *dir, wchar_t *fileName)
{
    wchar_t* path = 0;
    int size = 0;
    wchar_t *d = dir;
    wchar_t *f = fileName;
    while(*d != '\0')
    {
        d++;
        size++;
    }
    while(*f != '\0')
    {
        f++;
        size++;
    }
    path = new wchar_t[(size+=3) * sizeof(wchar_t)];
    int j = 0;
    while(j < size)
    {
        path[j] = '\0';
        j++;
    }
    int i;
    i = 0;
    while(*dir != '\0')
    {
        path[i] = *dir;
        i++;
        dir++;
    }
    path[i++] = '\\';
    wchar_t *t = fileName;  
    while(*t != '\0')
    {
        path[i] = *t;
        i++;
        t++;
    }
    path[i] = '\0';
    return path;
} 

void GetAllFiles(wchar_t* dir)
{
    wchar_t *p = 0;

    int i = 0;
    WIN32_FIND_DATA file;
    wchar_t *t = PathCreator(dir, L"*");
    HANDLE search_hendle = FindFirstFile(t, &file);
    if(search_hendle)
    {

        do
        {
            p = PathCreator(dir,file.cFileName);
            if(!is_directory(p))
            {
                std::wcout << p << std::endl;
            }
            else
            {
                GetAllFiles(p);
            }
            delete [] p;
        }
        while(FindNextFile(search_hendle, &file));

    }
    delete [] t;
    FindClose(search_hendle);
}


int _tmain(int argc, _TCHAR* argv[])
{
    GetAllFiles(L"C:\\Users");
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ens 8

所以你有了 "." 和目录搜索中的"..".

第一个条目是".",所以:

p = PathCreator(dir, file.cFilename)
Run Code Online (Sandbox Code Playgroud)

收益率:

"C:\Users\."
Run Code Online (Sandbox Code Playgroud)

然后是下一行:

if (!is_directory(p))
Run Code Online (Sandbox Code Playgroud)

总是假的,所以它只是不断递归:

GetAllFiles(p)
Run Code Online (Sandbox Code Playgroud)

永远......或直到你的筹码爆炸,以先到者为准;-)

我建议明确检查"." 和".."并跳过这些条目(也是MFC和Qt等有很好的目录处理类,但我想你想这样做).

我的修改:

    do
    {

        // I added this - guess I can't embolden code text
        if (wcscmp(file.cFileName,L".") == 0 || wcscmp(file.cFileName,L"..")==0)
            continue;

        p = PathCreator(dir,file.cFileName);
        if(!is_directory(p))
        {
            std::wcout << p << std::endl;
        }
        else
        {
            GetAllFiles(p);
        }
        delete [] p;
    }
    while(FindNextFile(search_hendle, &file));
Run Code Online (Sandbox Code Playgroud)