C使用malloc和realloc动态增加字符串长度

C using malloc and realloc to dynamically increase string length

目前正在学习 C 中的内存管理,我目前 运行正在解决随着循环迭代增加字符串长度的问题。

我试图找出逻辑上的方法是这样的:

// return string with "X" removed


char * notX(char * string){

   result = "";

   if(for int = 0; i < strlen(string); i++){
      if (string[i] != 'X') {
         result += string[i];
      }
   }

   return result;
}

在其他语言中很简单,但在 C 中管理内存使其具有挑战性。我 运行 遇到的困难是当我使用 malloc 和 realloc 来初始化和更改字符串的大小时。在我的代码中,我目前尝试过:

char * notX(char * string){

   char* res = malloc(sizeof(char*)); // allocate memory for string of size 1;
   res = ""; // attempted to initialize the string. Fairly certain this is incorrect
   char tmp[2]; // temporary string to hold value to be concatenated

   if(for int = 0; i < strlen(string); i++){
      if (string[i] != 'X') {

         res = realloc(res, sizeof(res) + sizeof(char*)); // reallocate res and increasing its size by 1 character
         tmp[0] = string[i];
         tmp[1] = '[=11=]';
         strcat(res, tmp);

      }
   }

   return result;
}

注意,我发现成功将结果初始化为一些大型数组,例如:

char res[100];

但是,我想了解如何在不初始化具有固定大小的数组的情况下解决这个问题,因为这可能会浪费内存 space,或者内存不足。

此代码中的 2 个主要错误:

  • mallocrealloc 函数调用 sizeof(char*) 的参数。在这种情况下,sizeof(char*) 的结果是指针的大小,而不是 char 的大小,因此您必须在 sizeof 函数中将 char* 替换为 char

  • res = ""; 不正确。您主要有内存泄漏,因为您丢失了指向 malloc 函数中刚刚分配的内存的指针,次要但同样重要,当通过 res 初始化为空字符串(或更好的常量字符串)调用 realloc 函数时,您有未定义的行为,在上面的初始化之后,内存不再是动态管理的。为了替代这个初始化,我认为将 memset 设置为 0 是最好的解决方案。

realloc 需要分配的字节数。 size 每添加一个字符到 res 就会递增。 size + 2 用于提供当前添加的字符和终止零。
检查 realloc 的 return。 NULL 表示失败。如果 realloc 失败,则使用 tmp 允许 res 的 return。

char * notX(char * string){

   char* res = NULL;//so realloc will work on first call
   char* tmp = NULL;//temp pointer during realloc
   size_t size = 0;
   size_t index = 0;

    while ( string[index]) {//not the terminating zero
        if ( string[index] != 'X') {
            if ( NULL == ( tmp = realloc(res, size + 2))) {//+ 2 for character and zero
                fprintf ( stderr, "realloc problem\n");
                if ( res) {//not NULL
                    res[size] = 0;//terminate
                }
                return res;
            }
            res = tmp;//assign realloc pointer back to res
            res[size] = string[index];
            ++size;
        }
        ++index;//next character
    }
    if ( res) {//not NULL
        res[size] = 0;//terminate
    }
   return res;
}