C Memory Leak passing argument?

Viewed 82

So my gcc compiler says:

=================================================================
==831==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x60c000001d3c at pc 0x7fcb29c87075 bp 0x7ffe0bf63e70 sp 0x7ffe0bf635e8
READ of size 121 at 0x60c000001d3c thread T0

I pass an char *list = argv[1] into a function. could this be the reason of this?

1 Answers

You're closing your file multiple times.

for (int i = 1; i < sl->count; i++)
{
    if (sl->stadt[i]->stadtId != s->stadtId)
    {
        s1 = sl->stadt[i];
        fprintf(file, "%d %s %d \n", sl->stadt[i]->stadtId, sl->stadt[i]->name, sl->stadt[i]->gebietId);
    }
fclose(file); // Being called several times on the loop!
} 

As you can see, the fclose(file) is inside the for loop, and from what i can see, it is called several times, that's what may be causing the issue.

What you can do: In case you want to close the file after printing in the file, you can put your fclose(file) inside the if statement and interrupt the loop like this:

for (int i = 1; i < sl->count; i++)
{
    if (sl->stadt[i]->stadtId != s->stadtId)
    {
        s1 = sl->stadt[i];
        fprintf(file, "%d %s %d \n", sl->stadt[i]->stadtId, sl->stadt[i]->name, sl->stadt[i]->gebietId);
        fclose(file);
        break;
    }
}

If the print is called multiple times, you just need to move the fclose(file) out of the for loop, like this:

for (int i = 1; i < sl->count; i++)
{
    if (sl->stadt[i]->stadtId != s->stadtId)
    {
        s1 = sl->stadt[i];
        fprintf(file, "%d %s %d \n", sl->stadt[i]->stadtId, sl->stadt[i]->name, sl->stadt[i]->gebietId);
    }
}
fclose(file);
Related