0

scanFolderPath - path of folder with files.

filesToScan - array of strings with the files name.

I have problem with the realloc line (the third line in the for loop). And I don't understand why! Thank you for helping programmers community ;)

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, "");
    }
}

2 Answers2

1

try

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

that way the contents of filepath are reallocated, and the pointer is returned to filepath

0

realloc returns new allocated block. You do not assign to anything so the reallocated memory is lost and your pointer is pointing to the invalid memory assuming realloc success).

The correct way of reallocating:

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

/* ... */

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

/* ... */

free(p)
0___________
  • 34,740
  • 4
  • 19
  • 48