c - 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
解决方案
- 您不检查 realloc 的结果。
- IMO最好将指针返回到新字符串而不是使用双指针。双指针可能导致难以跟踪内存泄漏,并且函数不适
const
用于字符串 - 例如字符串文字 - 您不
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 指针参数检查。
推荐阅读
- unicode - 使用 OleDB 将旧工具迁移到新的 Windows 版本时出现编码问题
- google-admin-sdk - 如何将 G Sutie Reseller API 的时间从数字转换为准确日期?
- php - 想这样搜索
- reactjs - 反应重定向到?提交请求而不是Rest api时的参数
- batch-file - 如何从名称中删除“set”文件的文件扩展名,以便调用该文件?
- autodesk-forge - 如何在 Forge Viewer 中移动部分 Gizmo
- sql-server - 如果您只从关系的一侧加入,是否仍然建议使用联结表?
- python - 启动 Python 队列时出现不可预测的行为
- python - 使用狮身人面像数学时的波兰字母
- android - 语言不变