I have a function that looks at a file of common passwords to see if any match the given encrypted password. If the password is in the set of common passwords, the program works, but if not I get an error message.
Even after some corrections, I get the following error message:
* Error in `./cs50': double free or corruption (out): 0x00007f9c7a061200 * Aborted
I seem to have a memory-leak somewhere preventing the program from continuing to the next step. Function code and valgrind output below.
Any advice?
bool check_common(char* pass, char* salt)
{
FILE* fp = fopen("topps.txt", "r");
if (fp == NULL) return false;
char current_word[9];
char* attempt = calloc(9, sizeof(char));
while (fscanf(fp, "%s\n", current_word) != EOF)
{
// in case reads fewer than 8 chars
for (int i=0;i<9;i++)
if (current_word[i] != '\0')
current_word[i] = '\0';
attempt = crypt(current_word, salt);
if (strcmp(pass, attempt) == 0)
{
printf("%s\n", current_word);
fclose(fp);
free(attempt);
return true;
}
}
free(attempt);
fclose(fp);
return false;
}
Valgrind output:
==22041== Invalid free() / delete / delete[] / realloc()
==22041== at 0x4C2BDEC: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==22041== by 0x4008F8: check_common (cs50.c:48)
==22041== by 0x4009DD: main (cs50.c:123)
==22041== Address 0x506f200 is 131200 bytes inside data symbol "_ufc_foobar"
==22041==
Failed.
==22041==
==22041== HEAP SUMMARY:
==22041== in use at exit: 27 bytes in 3 blocks
==22041== total heap usage: 4 allocs, 4 frees, 595 bytes allocated
==22041==
==22041== 27 bytes in 3 blocks are definitely lost in loss record 1 of 1
==22041== at 0x4C2CC70: calloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==22041== by 0x400864: check_common (cs50.c:34)
==22041== by 0x4009DD: main (cs50.c:123)
==22041==
==22041== LEAK SUMMARY:
==22041== definitely lost: 27 bytes in 3 blocks
==22041== indirectly lost: 0 bytes in 0 blocks
==22041== possibly lost: 0 bytes in 0 blocks
==22041== still reachable: 0 bytes in 0 blocks
==22041== suppressed: 0 bytes in 0 blocks
==22041==
==22041== For counts of detected and suppressed errors, rerun with: -v
==22041== ERROR SUMMARY: 4 errors from 2 contexts (suppressed: 0 from 0)
attempt
. Now with that freeing. I think the error probably comes from thefree(attempt);
command, and that's because of thechar* attempt = calloc(1,9);
command. Per thecalloc
'sman page
it's signature isvoid *calloc(size_t nmemb, size_t size);
. So if you want 9 members of typechar
, you should probably usechar* attempt = calloc(9, sizeof(char));
. Try it and let me know if it worked.