如何在不使用 realloc() 的情况下扩展字符串容量?

How to expand a string capacity without using realloc()?

我试图找到一种不使用 realloc 来扩展字符串容量的方法。例如,这段代码之间的主要区别是什么:

void insert(char *dest, char *src, int pos){

    char *temp = malloc(strlen(dest)+strlen(src)+1);

    /*
    malloc failure handling
    */

    strcpy(temp,dest);
    //rest of code

}

和:

void insert(char *dest, char *src, int pos){

    char *temp =(char*)realloc(dest,strlen(dest)+strlen(src)+1);
    /*
    realloc failure handling
    */

    dest = temp;
    //rest of code

}

或者有更好的方法吗?

请注意 srcdest 都是使用 malloc 初始化的。

malloc --> memcpy --> free 实际上就是 realloc 概念上所做的,只是稍微优化了一下。

并且因为这个优化这个问题

what is the major difference between this code

可以这样回答,前者在内存碎片方面可能更快更有效。


How to expand a string capacity without using realloc()?

如果 VLA* 可用(在 C99 之前没有,可能在 C11 中,在 C++ 中从来没有) 你知道最大输入的大小 这个大小永远不会导致堆栈溢出然后只有然后你可以做:

#include <stdio.h>
#include <string.h>

...

  char s1[] = "123";
  char s2[] = "456";
  char s3[] = "789";
  char s[strlen(s1) + strlen(s2) + strlen(s3) + 1];

  strcpy(s, s1);
  strcat(s, s2);
  strcat(s, s3);

  puts(s);

会看到

123456789

总而言之,如果开始玩 malloc() 就没有理由不转向它的堂兄 realloc()

realloc 等同于

void *my_realloc(void *old_p, size_t new_size) {
   void *new_p = malloc(new_size);
   if (!new_p)
      return NULL;

   size_t old_size = ...;
   if (old_size < new_size)
      memcpy(new_p, old_p, old_size);
   else
      memcpy(new_p, old_p, new_size);

   free(old_p);
   return new_p;
}

除了realloc可能扩展或收缩现有内存块。这将使它不必将字节从旧位置复制到新位置。

这意味着 realloc 至少与 malloc+memcpy+free 一样快,但可能更快。

主要区别在于,一个好的 realloc 实现会进行优化并尽可能跳过复制。 (这可以像检查内存中是否有 contiguos free space 来扩大你的分配,但这取决于内存的管理方式)。

如果您不想编写某种内存管理来在运行时处理未定义长度的字符串,没有比 realloc 更好的解决方案了。