在下面附带的代码中,我通过打开,将内容读入缓冲区,使用新密钥重新加密缓冲区然后写回文件来重新加密文件。
该程序作为基于python / django的服务器中的子进程运行。它将错误输出打印为:*** Error in
/ home / kunal / Documents / MyCrest / cloud / backend / mainbgw':double free或corruption(!prev):0x0000000000ecc250 ***`
清除已分配内存的最后一个语句free(ciphertext)
有时会出现错误,程序退出状态代码为139,即double free or corruption
如果我删除该语句,那么代码工作正常,但我希望通过释放分配的内存以正确的方式从函数返回。
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;
}
修改 该错误仅发生在大小为3kB或更大的文件中,因为139是内存损坏的错误代码或双重释放,我想这是前一种情况,因为我无处可去,我在代码中释放了两次内存位置。
答案 0 :(得分:2)
如果无法正确打开文件,则永远不会分配密文。由于它也没有设置为NULL,它将指向随机存储器位置并且free(密文)将崩溃。
在声明附近设置ciphertext = NULL
。