簡體   English   中英

C 問題與 memory 泄漏(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, "");
    }
}

嘗試

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

這樣文件路徑的內容被重新分配,指針返回到文件路徑

realloc 返回新分配的塊。 您沒有分配任何東西,因此重新分配的 memory 會丟失,並且您的指針指向無效的 memory (假設重新分配成功)。

重新分配的正確方法:

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

/* ... */

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

/* ... */

free(p)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM