首页 > 解决方案 > c中字符串的错误重新尺寸

问题描述

我正在尝试创建一个接收动态字符串并从中删除所有出现的字符的函数,该字符也作为参数传递。字符串最终应该包含足够的空间来包含未删除的字符

void delete(char *cad, char c){
    int i, cont = 0;
    char *aux = NULL;
        
    i = 0;
    while(cad[i] != '\0'){
        if(cad[i] != c){
            aux = (char*)realloc(aux, sizeof(char) * cont + 1);
            aux[cont] = cad[i];
            cont++;
        }
    i++;    
    }
    
    cad = (char*)realloc(cad, sizeof(char) * cont);
    i = 0;
    while(aux[i] != '\0'){
        cad[i] = aux[i];
        i++;
    }
    
}

现在我有一个segmentation fault

标签: cdynamic-memory-allocationc-stringsfunction-definition

解决方案


  1. 您不检查 realloc 的结果。
  2. IMO最好将指针返回到新字符串而不是使用双指针。双指针可能导致难以跟踪内存泄漏,并且函数不适const用于字符串 - 例如字符串文字
  3. 您不null character终止字符串。

在这个例子中,我没有改变你的分配算法,但在现实生活中更有效的方法是首先计算你需要分配多少内存,分配它,然后再次处理字符串:

char *delete(const char *cad, char c){
    size_t nchars = 0;
    char *aux = NULL;
    char *temp;
        
    while(*cad)
    {
        if(*cad != c)
        {
            temp = realloc(aux, sizeof(*temp) * nchars + 1);
            if(temp)
            {
                aux = temp;
                aux[nchars++] = *cad;
            }
            else
            {
                /* handle allocation error */
                free(aux);
                aux = NULL;
                break;
            }
        }
        cad++;
    }
    if(aux) aux[nchars] = 0;
    return aux;
}

一些小的变化:使用对象而不是类型 insizeof并且不强制转换malloc. 您还可以添加 NULL 指针参数检查。


推荐阅读