C内存泄漏问题(realloc函数)

C problem with memory leaks (realloc function)

scanFolderPath - 包含文件的文件夹路径。

filesToScan - 包含文件名的字符串数组。

我对 realloc 行有问题(for 循环中的第三行)。我不明白为什么!感谢您帮助程序员社区 ;)

char* filePath = malloc(0);
char* fileContent = 0;
char* partContent = 0;
FILE* fileToScan;
int i = 0, j = 0, virus = FALSE, flag = FALSE, counter = 0;
for (i = 0; i < amountOfFiles; i++)
{
    flag = FALSE;
    if (scanFolderPath != NULL && filesToScan[i] != NULL)
    {
        realloc(filePath, (sizeof(char) * (strlen(scanFolderPath) + 1 + strlen(filesToScan[i]))));
    }
    strcpy(filePath, "");
    getFilePath(filePath, scanFolderPath, filesToScan[i]);
    fileToScan = fopen(filePath, "rb");
    readFile(&fileContent, filePath);
    if (choice == '0')
    {
        virus = scanSingature(fileContent, virusSingature, getLength(fileToScan), virusSingatureLen);
        if (virus)
        {
            printf("%s - Infected!\n", filePath);
            fprintf(logsFile, "%s", filePath);
            fprintf(logsFile, "  Infected!\n");
        }
        else
        {
            printf("%s - Clean\n", filePath);
            fprintf(logsFile, ("%s", filePath));
            fprintf(logsFile, "  Clean\n");
        }
        fclose(fileToScan);
        strcpy(filePath, "");
    }
}

realloc returns 新分配的块。您没有分配给任何东西,因此重新分配的内存丢失并且您的指针指向无效内存(假设重新分配成功)。

重新分配的正确方法:

void *p = malloc(10);
void t;

/* ... */

t = realloc(p, 20);
if(t) p = t;            //check if the realloc was successful 

/* ... */

free(p)

尝试

filePath = realloc(filePath, (sizeof(char) * (strlen(scanFolderPath) + 1 + strlen(filesToScan[i]))));

这样 filepath 的内容被重新分配,指针返回到 filepath