In the below attached code I am re-encrypting a file by opening, reading the contents into a buffer, re-encrypting the buffer with a new key and then writing back to the file.
The program is being run as a subprocess in a python/django based server. which prints the error output as: *** Error in
/home/kunal/Documents/MyCrest/cloud/backend/mainbgw': double free or corruption (!prev): 0x0000000000ecc250 ***`
The last statement free(ciphertext)
to clean up the allocated memory gives me error sometimes where the program exits with a status code of 139 i.e double free or corruption
If I remove that statement then the code works perfectly, but I would like return from the function the right way by freeing up the allocated memory.
int update_encryption(char *fileName, char *base_k1, char *base_k1_new, const char* privateKey)
{
FILE *file;
size_t cipherlen,keylen;
unsigned char *ciphertext,*k1_temp,*k1_new_temp,*k1,*k1_new;
//read ciphertext from the file to be updated
file = fopen(fileName,"rb"); //open in read binary stream mode
if (file)
{
fseek (file, 0, SEEK_END);
cipherlen = ftell (file);
fseek (file, 0, SEEK_SET);
ciphertext = (unsigned char*) malloc(cipherlen*sizeof(unsigned char));
if (ciphertext)
{
fread (ciphertext, sizeof(unsigned char), cipherlen, file);
}
fclose (file);
}
//decrypt the data
if(!Base64Decode(base_k1, &k1_temp, &keylen))
{
k1 = (unsigned char*)malloc(sizeof(unsigned char)*374);
keylen = private_decrypt(k1_temp,keylen,(unsigned char *)privateKey, k1);
k1[keylen]='\0';
shaCrypt(ciphertext,(int)cipherlen, (const char *)k1, keylen);
free(k1_temp);
free(k1);
}
else
return 1;
//re-encrypt the data
if(!Base64Decode(base_k1_new,&k1_new_temp,&keylen))
{
k1_new = (unsigned char*)malloc(sizeof(unsigned char)*374);
keylen = private_decrypt(k1_temp,keylen,(unsigned char *)privateKey, k1_new);
k1_new[keylen]='\0';
shaCrypt(ciphertext,(int)cipherlen,(const char*)k1_new, keylen);
free(k1_new_temp);
free(k1_new);
}
else
return 1;
//write the encrypted data to file
file = fopen(fileName,"wb");
if (file)
{
fwrite(ciphertext, sizeof(unsigned char), cipherlen, file);
fclose(file);
}
else
return 1;
//free memory for ciphertext
if(ciphertext)
free(ciphertext);
return 0;
}
EDIT: The error occurs only for files with size 3kB or more, since 139 is the error code for memory corruption OR double free, I guess it is the former case as there is nowhere where I am freeing a memory location twice in my code.