【发布时间】:2021-02-20 20:58:38
【问题描述】:
编辑:问题是我没有为“\0”字符分配内存。
基本上,我在尝试运行此代码时遇到核心转储和损坏的最大尺寸错误,而不是用于 malloc 和动态内存。我的目标是连接两个字符串并使用分配的内存来做到这一点。第一个 'if' 将仅连接非 NULL 字符串,如果两者都是常规字符串,它将测量长度并为其分配内存。 代码可以编译,但执行时出现错误
int str_length(const char *str){
int i=0;
if(str == NULL) return (-1);
while( *(str+i) != '\0') i++;
return i;
}
我用这个函数来测量数组的大小。我不能使用公共库
char* str_concatenate(const char *stra, const char *strb){
char *concatenate;
int i=0;
if(stra==NULL || strb == NULL){
if(stra==NULL && strb == NULL) return (concatenate = NULL);
if(strb==NULL){
concatenate = (char*) malloc( sizeof(char)* (str_length(stra) + 1) ); //se a segunda e NULL, copia a primeira
do{
concatenate[i]=stra[i];
i++;
}while(stra[i]!='\0');
return concatenate;
}
else{
concatenate = (char*) malloc( sizeof(char)* (str_length(strb) + 1) ); //primeira NULL copia a segunda
do{
concatenate[i]=strb[i];
i++;
}while(strb[i]!='\0');
return concatenate;
}
}
int size_a = str_length(stra);
int size_b = str_length(strb);
int total = size_a + size_b;
concatenate = (char*) malloc( sizeof(char)*(total + 1) );
while(strb[i]!='\0'){
concatenate[size_b+i] = strb[size_b+i];
i++;
}
i=0;
while(stra[i]!='\0'){
concatenate[i] = stra[i];
i++;
}
return concatenate;
}
int main(){
char stra[] "first string"
char strb[] "second string"
str_concatenate(stra, strb);
return 0;
}
【问题讨论】:
-
str_lengh 是我创建的另一个函数。请不要有不完整和缺失的代码。请提供complete minimal verifiable example。另外,建议使用valgrind 之类的工具来帮助查找此类内存损坏。
-
一个问题是你没有 NUL 终止
concatenate缓冲区。所以返回的值不是一个有效的 C 字符串。 -
您可能没有为字符串末尾的
'\0'分配内存,并且代码肯定没有将'\0'放在字符串的末尾。 -
int total = tam_a + tam_b;你不能显示准确的真实代码,因为tam_a和tam_b是未声明的变量。 -
别忘了 C 中的
char字符串实际上称为 null-terminated 字节字符串。您需要将 null.terminator 字符'\0'添加到所有字符串中,当然需要为其分配空间(这意味着长度为X的字符串需要X + 1字符来适应终止符)。
标签: c string gcc command-line compiler-errors