const char *和free() [英] const char* and free()

查看:181
本文介绍了const char *和free()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出下一个代码示例,我无法释放参数const char* expression:

Given the next code example, I'm unable to free the parameter const char* expression:

// removes whitespace from a characterarray
char* removewhitespace(const char* expression, int length)
{
    int i = 0, j = 0;
    char* filtered;
    filtered = (char*)malloc(sizeof(char) * length);
    while(*(expression + i) != '\0')
    {
        if(!(*(expression + i) == ' '))
        {
            *(filtered + j) = *(expression + i);
            j++;
        }
        i++;
    }
    filtered[j] = '\0';
    free(expression); //this doesn't seem to work
    return filtered;
}

在返回此函数之前,我尝试释放expression参数中的数据,但似乎无法释放它.
我认为可能是因为它是一个常数,但是我了解到C中的字符数组应始终是一个常数.

Before I return this function, I try to free the data in the expression parameter but I can't seem to free it.
I think it is probably because it is a constant, but I learned that a character array in C always should be a constant.

我收到的错误消息在free(expression)行中,并且消息是:
expected void* but argument is of type const char * - compiler error

The error message I get is at the line with free(expression) and the message is:
expected void* but argument is of type const char * - compiler error

如何丢弃数据expression包含的内存?

How do I discard the memory that the data expression contains?

推荐答案

如果它是一个常量,则意味着不应删除它,因为它没有分配:调用者可以轻松地传递基于堆栈的数组您的方法,然后将其释放将是一件坏事.

If it's a constant, that implies that it shouldn't be deleted, because it wasn't allocated: the caller could easily have passed a stack-based array to your method, and freeing it would be a bad thing.

最常见的约定是,无论代码分配了什么数据,都应释放数据.释放该论点实际上不是您的例行职责,因为它无法知道这是否是合法的事情.

The most common convention is that whatever code allocates some data should free the data. It's really not your routine's responsibility to free that argument since it has no way of knowing if that's even a legitimate thing to do.

这篇关于const char *和free()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆