【发布时间】:2018-10-31 21:25:50
【问题描述】:
我正在用 C 编写代码。
我的算法的目标是将我们在数组 str 中找到的每个字符 c 加倍。
我必须运行一些测试,第一个测试我调用doubleChar("~/fichier.txt", '~'),它工作正常,但我的第二个测试是doubleChar("une commande # commentaire", '#'),我从标题中得到错误。
当我尝试调试它时,错误出现在 realloc 行上。
在调试器中我得到这个错误:
程序接收信号 SIGABRT 堆栈跟踪可在“调用堆栈”选项卡中获得
知道为什么吗?
这是我的代码:
char * doubleChar(const char *str, char c){
assert(str!=NULL);
char *newString=malloc(sizeof(str) * sizeof(char));
int a = 0;
while(str[a] != '\0'){
newString[a]=str[a];
a++;
}
newString[a]='\0';
int i = 0;
while(newString[i] != '\0'){
if(newString[i] == c){
newString = (char *)realloc(newString, stringLength(newString)*sizeof(char) + sizeof(char));
for(int j=stringLength(newString)+1; j>i; j--){
newString[j]=newString[j-1];
}
i++; //we add 1 to i so we don't find the char we just added
}
i++;
}
return newString;
}
【问题讨论】:
-
这可能需要大量的重新分配。考虑
doubleChar("!!!AhHa!!!", '!')一种更快的方法是在计算匹配字符数后循环遍历字符串,然后分配空间来保存原始字符串 + 匹配数 + 1(用于终止的 nul)。在第二个循环中复制字符,同时添加重复的字符。一个 malloc,没有 reallocs。 -
这真是个好主意!