C语言的内存泄漏问题(重定位函数)。

问题描述 投票:0回答:1

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, "");
    }
}
c memory-management memory-leaks heap-memory realloc
1个回答
1
投票

试试

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

这样一来,filepath的内容就会被重新分配,指针就会返回到filepath上。


0
投票

realloc返回新分配的块。你没有分配到任何东西,所以重新分配的内存丢失了,你的指针指向无效的内存,假设重新分配成功)。)

重新分配的正确方式。

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

/* ... */

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

/* ... */

free(p)
© www.soinside.com 2019 - 2024. All rights reserved.