c - 如何释放内存并同时返回指针?

标签 c memory memory-management malloc free

我有这些功能

char *hash(char *stringa, char *tipohash) {
    if (strcmp(tipohash, "md5") == 0) {
        stringa = md5(stringa);
    }
    return stringa;
}

char *md5(char *stringa) {
    unsigned char risultato[MD5_DIGEST_LENGTH];
    int i;
    char *hashfinale = malloc(sizeof(char) * MD5_DIGEST_LENGTH * 2);
    MD5((const unsigned char *)stringa, strlen(stringa), risultato);
    for (i = 0; i < MD5_DIGEST_LENGTH; i++) {
        sprintf(hashfinale + 2 * i, "%02x", risultato[i]);
    }
    return (char *)hashfinale;
}

如何在不丢失字符串值的情况下返回 (char *)hashfinale 进行释放?

这是来电者

char *hashlinea = hash(stringa, hashType);

最佳答案

基本上有两种方法可以解决该问题,并且没有一种方法涉及您的代码调用free


第一种方法是与现在不做任何不同的事情,除了添加文档,以便您的 hash 函数的用户知道代码必须在返回的值上调用 free指针:

// This is the code using your function
char *hashlinea = hash(stringa,hashType);

// Some code using hashlinea

free(hashlinea);

第二种方法是将指针传递给现有数组,并且您的代码使用该数组而不是使用 malloc 分配它:

char hashlinea[MD5_DIGEST_LENGTH*2];
hash(stringa, hashType, hashlinea);

为此,您的 hash 函数需要将第三个参数传递给 md5 函数,该函数应该使用它而不是分配内存:

char *md5(char *stringa, char *hashfinale){
    unsigned char risultato[MD5_DIGEST_LENGTH];
    int i;
    // No memory allocation here
    MD5((const unsigned char *)stringa, strlen(stringa), risultato);
    for(i = 0; i < MD5_DIGEST_LENGTH; i++) {
        sprintf(hashfinale + 2*i,"%02x",risultato[i]);
    }
    return hashfinale;
}

关于c - 如何释放内存并同时返回指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62793908/

相关文章:

c - 什么是 "FPE_FLTSUB: subscript out of range"信号?

ios - 以编程方式获取 iOS 上的低内存日志/报告

c - 是否会为 typedef 结构指针分配内存?

c++ - 分配器感知容器分配是如何实现的?

C#pragma 是预处理还是编译时操作?

c - 处理用户输入中的 EOF

c# - 什么定义了内存流的容量

c++ - 使用和不使用 new 运算符初始化对象

c - 可执行代码的高性能 malloc 实现

c - 为启动时运行的 linux 内核添加代码