gpt4 book ai didi

c - 将数据动态复制到二维字符数组时发生访问冲突

转载 作者:行者123 更新时间:2023-11-30 19:07:31 24 4
gpt4 key购买 nike

请引用我的递归代码,该代码解析具有大量文件的目录。代码复制字符数组中的所有文件路径。我是否遗漏了在递归调用中遇到访问冲突的内容?提前致谢

// global variables
int iFileCount = 0;
char *szFilePath[MAX_PATH];

// Recursive function to get all files in the path specified
void FindFilesRec(const char *szDir)
{
int i, iRet;
HANDLE hFind;
char sPath[MAX_PATH];
WIN32_FIND_DATA ffd;
LARGE_INTEGER filesize;

sprintf(sPath, "%s\\*.*", szDir);

hFind = FindFirstFile(sPath, &ffd);
if (INVALID_HANDLE_VALUE == hFind)
{
_tprintf(TEXT("FindFirstFile error"));
return;
}

i = 0;
for (i;;i++)
{
if ((strcmp(ffd.cFileName, ".") != 0) && (strcmp(ffd.cFileName, "..") != 0))
{
sprintf(sPath, "%s\\%s", szDir, ffd.cFileName);
if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
_tprintf(TEXT("\n %s <DIR>\n"), ffd.cFileName);
{
FindFilesRec(sPath);
}
}
else
{
filesize.LowPart = ffd.nFileSizeLow;
filesize.HighPart = ffd.nFileSizeHigh;
_tprintf(TEXT("\n %s %ld bytes\n"), ffd.cFileName, filesize.QuadPart);
szFilePath[iFileCount] = (char *)malloc(sizeof(char) * strlen(sPath) + 1);
szFilePath[iFileCount][strlen(sPath)] = '\0';
memcpy(szFilePath[iFileCount], sPath, strlen(sPath));
iFileCount++;
}
}

iRet = FindNextFile(hFind, &ffd);
if (0 == iRet)
{
break;
}
}

FindClose(hFind);

return;
}

最佳答案

这个问题与递归函数完全无关,递归函数似乎工作正常(尽管我没有检查细节)。

char *szFilePath[MAX_PATH]; 声明一个指向 char*MAX_PATH 指针数组。因此,一旦 iFileCount 超过值 MAX_PATH,您就开始覆盖内存,这会导致未定义的行为。

你基本上是这样做的:

char *szFilePath[MAX_PATH];
int iFileCount;

void foo()
{
char sPath[] = "bar";
szFilePath[iFileCount] = (char *)malloc(sizeof(char) * strlen(sPath) + 1);
szFilePath[iFileCount][strlen(sPath)] = '\0';
memcpy(szFilePath[iFileCount], sPath, strlen(sPath));
iFileCount++;
}

int main()
{
for (int i = 0; i < 100000; i++)
foo(); // problem if i exceeds MAX_PATH
}

这也会像你的程序一样失败。

您需要以不同的方式处理szFilePath

关于c - 将数据动态复制到二维字符数组时发生访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46711225/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com