繁体   English   中英

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] = '\0';
         strcat(res, tmp);

      }
   }

   return result;
}

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

char res[100];

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

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

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;
}

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

  • mallocrealloc函数带有调用sizeof(char*) 在这种情况下的sizeof(字符*)的结果是一个指针的大小,而不是一个char的,所以你要替换char*char的功能的sizeof。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM