【问题标题】:How am I corrupting memory with this code?我如何用这段代码破坏内存?
【发布时间】: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_atam_b 是未声明的变量。
  • 别忘了 C 中的 char 字符串实际上称为 null-terminated 字节字符串。您需要将 null.terminator 字符 '\0' 添加到所有字符串中,当然需要为其分配空间(这意味着长度为 X 的字符串需要 X + 1 字符来适应终止符)。

标签: c string gcc command-line compiler-errors


【解决方案1】:

请注意,您正在重置i,因此实际上您是在第二个while 中覆盖concatenate,您应该尝试使用不同的变量来跟踪concatenate 的索引,例如:

Live demo

//...
// size of char is always 1 byte, no need to include in malloc
concatenate = malloc(total + 1); // don't forget the null byte

i = 0;

while (strb[i] != '\0')
{
    concatenate[i] = strb[i];
    i++;
}

int j = 0;

while (stra[j] != '\0')
{
    concatenate[i] = stra[j];
    i++;
    j++;
}
concatenate[i] = 0; // null terminate the string, the same goes for the others
//...

【讨论】:

    猜你喜欢
    • 2022-08-03
    • 2015-04-13
    • 1970-01-01
    • 2019-02-20
    • 2017-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-27
    相关资源
    最近更新 更多